1. Objectives
- Treat a grey image as a table of numbers and compute its gradients Ix and Iy (change to the right and downwards).
- Build a two-rule Mamdani fuzzy system that decides, for every pixel, whether it lies on an edge.
- Apply the fuzzy system to a whole image with NumPy arrays (no slow loop over pixels).
- Compare the fuzzy edge map with the classic Sobel and Canny detectors in OpenCV.
2. Word Bank
Word | Simple meaning | Real-world example |
|---|---|---|
Pixel | One small square of a digital image; in a grey image it holds one number (0 = black, 1 = white) | A phone photo has about 12 million pixels |
Edge | A place where the grey level changes suddenly - the border of an object | The outline of a cotton boll against the sky |
Gradient | How much the grey level changes from one pixel to the next | Ix = 0.6 at the border of the bright rectangle |
Edge map | A new image that is dark on edges and light elsewhere | The outline drawing a child makes of a photo |
Sobel / Canny | Classic (non-fuzzy) edge detectors built into OpenCV | Used in number-plate readers at toll plazas |
Precision / recall | Share of found pixels that are real edges / share of real edges that were found | Found 329, all real: precision 1.0 |
3. Background
Images are numbers
A grey image is a 2-D array: I[row, column] is the brightness of one pixel, 0 (black) to 1 (white). edgeimages.shapes() makes an 80 x 80 test image: a bright rectangle (0.8), a circle (0.55) and a faint triangle (0.35) on a dark background (0.2). Because we made it ourselves we know exactly where the true edges are: true_edges(I).
Gradients
At an edge the brightness changes suddenly. Ix[r, c] = I[r, c+1] - I[r, c] (change to the right) and Iy[r, c] = I[r+1, c] - I[r, c] (change downwards). In flat areas both are 0; at the border of the rectangle Ix or Iy is about 0.6.
The fuzzy system (MATLAB example in Python)
MATLAB's Fuzzy Logic Toolbox example 'Fuzzy Logic Image Processing' uses two inputs Ix and Iy, each with one term zero = Gaussian with mean 0 and sigma 0.1, and one output Iout with terms white = triangle [0.1, 1, 1] and black = triangle [0, 0, 0.7]. Rule 1: IF Ix IS zero AND Iy IS zero THEN Iout IS white. Rule 2: IF Ix IS NOT zero OR Iy IS NOT zero THEN Iout IS black. AND = min, OR = max, NOT = 1 - x, then clip, max and centroid exactly as in P09a. Flat pixels come out about 0.70 (light), strong edges about 0.23 (dark). Pixels below 0.5 are called edge pixels.
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) |
4. Time Plan (50 minutes)
Minutes | Activity | Part |
|---|---|---|
0-5 | Background: images as arrays; gradients; the two rules | 1-3 |
5-10 | Guided warm-up: look at the image; one row of gradients | 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. Look at the test image
Make the test image, print its size and grey levels, and save a picture of it.
import numpy as np import matplotlib.pyplot as plt import skfuzzy as fuzz from edgeimages import shapes, true_edges, score I = shapes() # 80 x 80 grey image, values 0 (black) to 1 (white) print("size:", I.shape, " grey levels:", np.unique(I)) print("true edge pixels:", true_edges(I).sum()) plt.figure(figsize=(3.2, 3.2)); plt.imshow(I, cmap="gray", vmin=0, vmax=1); plt.title("shapes()"); plt.axis("off") plt.tight_layout(); plt.savefig("shapes.png", dpi=120) |
Output size: (80, 80) grey levels: [0.2 0.35 0.55 0.8 ] true edge pixels: 329 |
A2. One row of gradients
Row 20 crosses the left side of the bright rectangle (columns 7-12). Compute the change to the right by hand with NumPy.
# ... set-up: imports and the test image (as shown earlier) ... row = I[20, 7:13] print("grey :", row) print("Ix :", np.round(row[1:] - row[:-1], 2), " <- the jump at the edge") |
Output grey : [0.2 0.2 0.2 0.8 0.8 0.8] Ix : [0. 0. 0.6 0. 0. ] <- the jump at the edge |
Part B - Predict the Output
Write your prediction BEFORE running the code. Then run it and correct yourself in a different colour.
B1.
import numpy as np r = np.array([0.2, 0.2, 0.8, 0.8]) Ix = np.zeros_like(r); Ix[:-1] = r[1:] - r[:-1] print(Ix) |
My prediction |
B2.
import numpy as np, skfuzzy as fuzz print(np.round(fuzz.gaussmf(np.array([0, 0.1, 0.3]), 0, 0.1), 3)) |
My prediction |
B3.
import skfuzzy as fuzz zx, zy = float(fuzz.gaussmf(0.6, 0, 0.1)), float(fuzz.gaussmf(0.0, 0, 0.1)) print(f"white rule {min(zx, zy):.3f} black rule {max(1 - zx, 1 - zy):.3f}") |
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 and the test image (as shown earlier) ... I8 = (I * 255).astype(np.uint8) # the image as a camera gives it: whole numbers 0-255 Ix = I8[:, 1:] - I8[:, :-1] print(I8[20, 39:42], "->", Ix[20, 39:41]) # right side of the rectangle: bright -> dark |
It runs and prints [204 204 51] -> [ 0 103] |
Bug, why it happens, and the fixed line(s) |
C2.
# ... set-up: imports and the test image (as shown earlier) ... Ix = I[:, 1:] - I[:, :-1] # 80 x 79 Iy = I[1:, :] - I[:-1, :] # 79 x 80 zx, zy = fuzz.gaussmf(Ix, 0, 0.1), fuzz.gaussmf(Iy, 0, 0.1) w_white = np.fmin(zx, zy) |
Bug, why it happens, and the fixed line(s) |
C3.
# ... set-up: imports and the test image (as shown earlier) ... 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 Ix, Iy = gradients(I) zx, zy = fuzz.gaussmf(Ix, 0, 0.1), fuzz.gaussmf(Iy, 0, 0.1) w_black = np.fmin(1 - zx, 1 - zy) # rule 2 strength print("pixels where the black rule fires above 0.5:", (w_black > 0.5).sum()) |
It runs and prints pixels where the black rule fires above 0.5: 21 |
Bug, why it happens, and the fixed line(s) |
Part D - Graded Tasks (10 marks)
Task | Level | Title | Marks |
|---|---|---|---|
T1 | Easy | Gradient images | 3 |
T2 | Medium | The fuzzy edge detector | 3 |
T3 | Challenge | Fuzzy against Sobel and Canny | 4 |
Total | 10 |
Task 1 (Easy, 3 marks): Gradient images
Write gradients(I) that returns Ix and Iy with the same size as I (pad with 0). Print how many pixels have Ix != 0 and Iy != 0, and the largest |Ix| and |Iy|. Save a figure with three panels: the image, |Ix| and |Iy| (gradients.png).
Sample run (your output must match):
Output shapes: (80, 80) (80, 80) (80, 80) Ix != 0: 170 pixels, largest |Ix| = 0.60 Iy != 0: 180 pixels, largest |Iy| = 0.60 |
Your code (or attach the file) |
Task 2 (Medium, 3 marks): The fuzzy edge detector
Write fuzzy_edges(I, sigma=0.1) with the two rules of the background (Gaussian 'zero' terms, white [0.1, 1, 1], black [0, 0, 0.7], min/max/1 - x, clip, max, centroid) for ALL pixels at once with NumPy. Print the smallest and largest output, the number of edge pixels (output < 0.5), and their score against true_edges(I). Save fuzzy.png.
Sample run (your output must match):
Output output from 0.230 (strong edge) to 0.703 (flat) edge pixels: 329 true edge pixels: 329 precision, recall, F1: (1.0, 1.0, 1.0) |
Your code (or attach the file) |
Task 3 (Challenge, 4 marks): Fuzzy against Sobel and Canny
Run two classic OpenCV detectors on the same image: Sobel (cv2.Sobel in x and y, magnitude = sqrt(gx^2 + gy^2), edge if magnitude > 0.5) and Canny (cv2.Canny on the uint8 image with thresholds 50 and 150). Print a table with the number of edge pixels and the score of each method (fuzzy, Sobel, Canny), and save a 3-panel figure compare.png. Which method draws thicker edges, and why?
Sample run (your output must match):
Output method pixels precision, recall, F1 fuzzy 329 (1.0, 1.0, 1.0) Sobel 560 (1.0, 1.0, 1.0) Canny 313 (1.0, 1.0, 1.0) |
Your code (or attach the file) |
Part E - Post-Lab Questions (finish as homework if time runs out)
E1. Why do we convert an 8-bit image (0-255) to float 0-1 before computing gradients?
Your answer |
E2. Write the two rules of the fuzzy edge detector and say which operator is used for AND, OR and NOT.
Your answer |
E3. Why is a flat pixel about 0.70 and a strong edge about 0.23?
Your answer |
Marking Rubric (applied to Part D)
Criterion | Full | Partial | None |
|---|---|---|---|
Code runs without errors | Runs fully | Small fixable error | Does not run |
Padded gradients, counts and 3-panel figure | All correct | One slip | Missing |
Vectorised fuzzy detector: rules, centroid, 329 edges, score | Correct | Partly correct | Missing |
Sobel and Canny compared in a table; thickness explained | Clear and correct | Partly correct | Missing |
Submission
- Make a folder RollNo_P14a with task1.py, task2.py, task3.py (or P14a.ipynb) and the three PNG figures.
- Upload the zipped folder to the LMS / Google Classroom by the end of the day.
- Copy Task 2 code and output into your Lab Book (Practical 14a page).
- Keep gradients() and fuzzy_edges() - P14b tunes the detector, adds noise and tries a leaf image.