1. Objectives
- Explain how the width sigma of the 'zero' sets controls the sensitivity of the fuzzy edge detector.
- Measure how camera noise damages edge detection, using precision, recall and F1 against known true edges.
- Improve the detector by smoothing first and choosing sigma with a grid search; compare with Sobel and Canny.
- Apply the tuned detector to a noisy leaf image with a disease spot and judge the result.
2. Word Bank
Word | Simple meaning | Real-world example |
|---|---|---|
Noise | Small random errors in pixel values from the camera sensor, poor light or compression | Grainy photos taken at night |
Smoothing (blur) | Replacing each pixel by a weighted average of its neighbours, which hides small random changes | cv2.GaussianBlur(I, (3, 3), 1) |
Sensitivity | How small a change the detector reports as an edge | sigma 0.05 = very sensitive |
Grid search | Trying every combination of settings from a list and keeping the best score | 3 blurs x 6 sigmas = 18 tries |
F1 score | One number that balances precision and recall (1.0 = perfect) | F1 0.48 with noise, 0.97 after tuning |
Leaf disease spot | A dark patch on a leaf caused by a fungus or bacteria | Cotton leaf curl, wheat rust |
3. Background
What sigma does
fuzzyedge.fuzzy_edges(I, sigma) is the P14a detector. sigma is the width of the Gaussian 'zero' set of Ix and Iy. A small sigma says that even a tiny change is 'not zero' - the detector is very sensitive and also reports noise. A large sigma ignores small changes - faint edges disappear. Choosing sigma is choosing what counts as an edge.
Noise and smoothing
A camera adds small random errors to every pixel (edgeimages.add_noise). Gradients turn these into many small changes, and a sensitive detector marks them as edges. Smoothing first (cv2.GaussianBlur, kernel size 3 x 3 or 5 x 5 - it must be ODD) averages the noise away, but it also spreads a sharp edge over two or three pixels, so its gradient becomes smaller and sigma must be made smaller too.
Measuring quality
Because shapes() is made by code, true_edges() gives the real edge pixels. score(true, found) returns precision (share of found pixels that are real edges), recall (share of real edges that were found) and F1 = 2PR / (P + R), allowing a one-pixel shift. Precision falls when noise is reported as edges; recall falls when real edges are missed.
Data files for this lab
edgeimages.py
"""edgeimages.py - test images for CS-511 P14a/P14b (fuzzy edge detection). Grey levels 0 (black) to 1 (white). shapes(): rectangle, circle and a faint triangle on a dark background. leaf(): a leaf on white paper with a faint midrib (vein) and a dark disease spot. add_noise(img, sd, seed): camera noise. true_edges(img): the real edge pixels of a CLEAN test image (any change of grey level to the right or below).""" import numpy as np def shapes(): r, c = np.mgrid[0:80, 0:80] img = np.full((80, 80), 0.2) img[10:36, 10:41] = 0.8 # bright rectangle ... (48 data rows in total - copy the full file from the lab folder) |
fuzzyedge.py
"""fuzzyedge.py - the P14a fuzzy edge detector (Mamdani, 2 rules), for CS-511 P14b. gradients(I) -> Ix, Iy; fuzzy_edges(I, sigma) -> Iout (about 0.70 on flat areas, about 0.23 on strong edges).""" import numpy as np import skfuzzy as fuzz X = np.linspace(0, 1, 101) WHITE = fuzz.trimf(X, [0.1, 1, 1]) BLACK = fuzz.trimf(X, [0, 0, 0.7]) def gradients(I): Ix = np.zeros_like(I); Ix[:, :-1] = I[:, 1:] - I[:, :-1] # change to the right Iy = np.zeros_like(I); Iy[:-1, :] = I[1:, :] - I[:-1, :] # change downwards return Ix, Iy def fuzzy_edges(I, sigma=0.1): Ix, Iy = gradients(I) zx, zy = fuzz.gaussmf(Ix, 0, sigma), fuzz.gaussmf(Iy, 0, sigma) # degree of 'zero' w_white = np.fmin(zx, zy) # IF Ix IS zero AND Iy IS zero THEN white w_black = np.fmax(1 - zx, 1 - zy) # IF Ix IS NOT zero OR Iy IS NOT zero THEN black agg = np.fmax(np.fmin(WHITE, w_white[..., None]), np.fmin(BLACK, w_black[..., None])) return (agg * X).sum(-1) / agg.sum(-1) # centroid of every pixel |
4. Time Plan (50 minutes)
Minutes | Activity | Part |
|---|---|---|
0-5 | Background: sigma, noise, smoothing, the score | 1-3 |
5-10 | Guided warm-up: noise damages the edge map; smoothing | Part A |
10-13 | Predict the output | Part B |
13-17 | Bug hunt | Part C |
17-47 | Graded tasks 1-3 | Part D |
47-50 | Wrap-up; post-lab questions set as homework | Part E |
Part A - Guided Warm-up (type, run, observe)
A1. Noise damages the edge map
Add camera noise to the test image and run the P14a detector on the clean and the noisy image.
import numpy as np import matplotlib.pyplot as plt import cv2 import skfuzzy as fuzz from edgeimages import shapes, leaf, add_noise, true_edges, score from fuzzyedge import fuzzy_edges I = shapes(); T = true_edges(I) # clean image and its true edges N = add_noise(I, 0.05, seed=1) # the same image with camera noise (standard deviation 0.05) for name, img in (("clean", I), ("noisy", N)): e = fuzzy_edges(img) < 0.5 print(f"{name}: edge pixels {e.sum():>5} precision, recall, F1 = {score(T, e)}") fig, ax = plt.subplots(1, 2, figsize=(5.6, 2.9)) ax[0].imshow(N, cmap="gray", vmin=0, vmax=1); ax[0].set_title("noisy image", fontsize=9) ax[1].imshow(~(fuzzy_edges(N) < 0.5), cmap="gray"); ax[1].set_title("fuzzy edges (sigma 0.1)", fontsize=9) for a in ax: a.axis("off") plt.tight_layout(); plt.savefig("noisy.png", dpi=120) |
Output clean: edge pixels 329 precision, recall, F1 = (1.0, 1.0, 1.0) noisy: edge pixels 1296 precision, recall, F1 = (0.317, 0.991, 0.48) |
A2. Smoothing hides the noise
Measure the noise in a flat patch of background (rows 2-8, columns 50-76) before and after a 3 x 3 Gaussian blur.
# ... set-up: imports, the clean and the noisy test image (as shown earlier) ... B = cv2.GaussianBlur(N, (3, 3), 1) print(f"flat patch spread (std) before blur {N[2:9, 50:77].std():.3f}, after blur {B[2:9, 50:77].std():.3f}") print("rectangle edge, row 20, columns 38-43") print(" noisy :", np.round(N[20, 38:44], 2)) print(" blurred:", np.round(B[20, 38:44], 2), " <- the step is spread over more pixels") |
Output flat patch spread (std) before blur 0.049, after blur 0.019 rectangle edge, row 20, columns 38-43 noisy : [0.72 0.78 0.73 0.16 0.19 0.2 ] blurred: [0.79 0.8 0.64 0.35 0.18 0.21] <- the step is spread over more pixels |
Part B - Predict the Output
Write your prediction BEFORE running the code. Then run it and correct yourself in a different colour.
B1.
import skfuzzy as fuzz for sigma in (0.1, 0.3): z = float(fuzz.gaussmf(0.15, 0, sigma)) print(f"sigma {sigma}: 'zero' degree of a change of 0.15 = {z:.3f}, black rule = {1 - z:.3f}") |
My prediction |
B2.
import numpy as np from fuzzyedge import fuzzy_edges out = fuzzy_edges(np.full((5, 5), 0.4)) print(round(out.min(), 3), round(out.max(), 3), (out < 0.5).sum()) |
My prediction |
B3.
import numpy as np, cv2 a = np.zeros((5, 5)); a[2, 2] = 1.0 # one bright noisy pixel print(np.round(cv2.GaussianBlur(a, (3, 3), 1)[2], 3)) |
My prediction |
Part C - Bug Hunt
Each program has ONE bug. Some crash with an error message; others run but give a wrong answer (silent logic error - the dangerous kind). Find the bug, explain it and write the fix.
C1.
# ... set-up: imports, the clean and the noisy test image (as shown earlier) ... B = cv2.GaussianBlur(N, (4, 4), 1) print((fuzzy_edges(B, 0.05) < 0.5).sum()) |
Bug, why it happens, and the fixed line(s) |
C2.
# ... set-up: imports, the clean and the noisy test image (as shown earlier) ... edges = fuzzy_edges(I) > 0.5 # edge pixels print("edge pixels:", edges.sum()) |
It runs and prints edge pixels: 6071 |
Bug, why it happens, and the fixed line(s) |
C3.
# ... set-up: imports, the clean and the noisy test image (as shown earlier) ... e = fuzzy_edges(N) < 0.5 p, r, f = score(e, T) print(f"precision {p} recall {r} F1 {f}") |
It runs and prints precision 0.991 recall 0.317 F1 0.48 |
Bug, why it happens, and the fixed line(s) |
Part D - Graded Tasks (10 marks)
Task | Level | Title | Marks |
|---|---|---|---|
T1 | Easy | What sigma does | 3 |
T2 | Medium | Noise: four detectors compared | 3 |
T3 | Challenge | Tune by grid search, then a leaf | 4 |
Total | 10 |
Task 1 (Easy, 3 marks): What sigma does
On the CLEAN image run fuzzy_edges with sigma = 0.05, 0.1, 0.2 and 0.3. Print the number of edge pixels and the score for each, and save a 4-panel figure sigma.png. Which shape loses its edges first as sigma grows, and why?
Sample run (your output must match):
Output sigma 0.05 edge pixels 329 (1.0, 1.0, 1.0) sigma 0.1 edge pixels 329 (1.0, 1.0, 1.0) sigma 0.2 edge pixels 218 (1.0, 0.663, 0.797) sigma 0.3 edge pixels 113 (1.0, 0.343, 0.511) |
Your code (or attach the file) |
Task 2 (Medium, 3 marks): Noise: four detectors compared
On the NOISY image N compare: (1) fuzzy, sigma 0.1; (2) blur with cv2.GaussianBlur(N, (3, 3), 1), then fuzzy with sigma 0.05; (3) Sobel magnitude > 0.5 (as in P14a); (4) Canny 50/150 on the uint8 image. Print a table of edge pixels and scores. Which is best, and what goes wrong with the worst one?
Sample run (your output must match):
Output method pixels precision, recall, F1 fuzzy, sigma 0.1 1296 (0.317, 0.991, 0.48) blur + fuzzy, 0.05 665 (1.0, 0.942, 0.97) Sobel > 0.5 653 (0.881, 1.0, 0.936) Canny 50/150 1606 (0.224, 1.0, 0.365) |
Your code (or attach the file) |
Task 3 (Challenge, 4 marks): Tune by grid search, then a leaf
Grid search on N: blur in (none, (3, 3) sigma 1, (5, 5) sigma 1) x fuzzy sigma in (0.03, 0.05, 0.07, 0.1, 0.15, 0.2). Print the best three settings by F1. Then apply the best setting to a noisy leaf, L = add_noise(leaf(), 0.05, seed=2), print its score against true_edges(leaf()) and save leaf.png (noisy leaf and edge map). Is the leaf outline found? the disease spot? the faint midrib (vein)?
Sample run (your output must match):
Output blur 3x3 sigma 0.05 F1 0.97 blur 3x3 sigma 0.03 F1 0.941 blur 5x5 sigma 0.03 F1 0.939 leaf with blur 3x3, sigma 0.05: edge pixels 668, score (1.0, 0.666, 0.799) midrib true edge pixels 122, found 5 disease spot true edge pixels 49, found 48 |
Your code (or attach the file) |
Part E - Post-Lab Questions (finish as homework if time runs out)
E1. What happens to the edge map when sigma is made larger? When it is made smaller?
Your answer |
E2. Why must the fuzzy sigma be made smaller after blurring the image?
Your answer |
E3. Give one real use of edge detection in agriculture and say what a missed edge (low recall) would cost there.
Your answer |
Marking Rubric (applied to Part D)
Criterion | Full | Partial | None |
|---|---|---|---|
Code runs without errors | Runs fully | Small fixable error | Does not run |
Sigma sweep: table, figure, which shape goes first and why | All correct | One slip | Missing |
Four detectors on the noisy image: table and explanation | Correct and explained | Partly correct | Missing |
Grid search, best setting applied to the leaf, judgement | Clear and correct | Partly correct | Missing |
Submission
- Make a folder RollNo_P14b with task1.py, task2.py, task3.py (or P14b.ipynb), sigma.png and leaf.png.
- Upload the zipped folder to the LMS / Google Classroom by the end of the day.
- Copy Task 3 code and output into your Lab Book (Practical 14b page).
- Optional: try your detector on your own phone photo: cv2.imread('photo.jpg', cv2.IMREAD_GRAYSCALE) / 255, resized to about 200 x 200.