Due: Friday, Feb. 12, 2027.
This laboratory illustrates the concepts of pixel neighborhoods and connected pixel sets. You compute the set of all pixels connected to a seed pixel. Then you use it to segment the image into connected components.
This is the one lab in the course that uses C. Region growing visits one pixel at a time, and each step depends on the steps before it. In Module 1 you write it in Python. In Module 2 you write it in C, check that all versions agree, and time them.
You direct Claude, or another agentic AI, to write the code from the definitions and signatures on this page. You run the experiments, explain the results, and explain how the C code works. You are graded on your specification, your checks, and your reading of the results.
lab5-data.zip
(190 KB) holds img22g.png, an 8-bit grayscale PNG, 768 pixels
wide and 512 pixels tall. In the folder that holds
lab5.py:
wget https://charlesbouman.org/ece63700/labs/lab5-data.zip unzip lab5-data.zip
lab5.py and C code in
connect.c. Use the labs conda
environment from Lab 2, with NumPy (not PyTorch) and
matplotlib.lab5.py holds only functions. Run experiments from a
separate script that imports it.uint8 and do not scale it. The thresholds
\(T = 1, 2, 3\) are in gray levels.connected_set in Module 1 is pure Python, with no
vectorized NumPy operations.| Item | Experiment | Input | Function and settings |
|---|---|---|---|
| D1 | Connected set of the seed (Step 3) | img22g.png |
connected_set, seed \((m, n) = (90, 134)\),
\(T = 1, 2, 3\), label 1, 4-point neighborhood |
| D2 | Segmentation in Python (Step 4) | img22g.png |
segment with connected_set,
\(T = 1, 2, 3\), keep components with more than 100 pixels |
| D3 | C against Python (Step 8) | img22g.png |
the runs of D1 and D2 repeated with connected_set_c,
and the runs of D2 repeated with segment_c |
| D4 | Timings (Step 9) | img22g.png |
seed \((90, 134)\) with \(T = 2\), smallest of 5 runs; the three segmentations with \(T = 1, 2, 3\), smallest of 3 runs |
| D5 | How the C code works (Step 10) | connect.c |
— |
lab5.py
Copy these helpers into lab5.py.
import ctypes
import os
import numpy as np
from PIL import Image
def load_image(path):
"""Read an 8-bit grayscale image as an (H, W) uint8 array."""
return np.ascontiguousarray(np.asarray(Image.open(path).convert("L"), dtype=np.uint8))
def save_image(x, path):
"""Write an (H, W) uint8 array as an 8-bit grayscale PNG."""
Image.fromarray(np.asarray(x, dtype=np.uint8)).save(path)
def save_label_image(labels, path):
"""Write a label image as a color PNG: label 0 black, others fixed random colors."""
k = int(labels.max())
colors = np.random.default_rng(0).integers(40, 256, size=(k + 1, 3), dtype=np.uint8)
colors[0] = 0
Image.fromarray(colors[labels]).save(path)
Let \(x_s\) be the pixel value at the lattice point \(s = (m, n)\). We use a 4 point neighborhood, so the neighbors of \(s\) are
$$ \partial s = \big\{ (m-1, n), \ (m+1, n), \ (m, n-1), \ (m, n+1) \big\} \ . \tag{1} $$We also use a free boundary, so pixels along the boundary of the image have fewer than 4 neighbors each. Two neighboring lattice points \(r \in \partial s\) are connected neighbors if \(|x_s - x_r| \le T\), where \(T\) is a fixed threshold. We denote the connected neighbors of \(s\) by the set
$$ c(s) = \big\{ r \in \partial s \ : \ |x_s - x_r| \le T \big\} \ . \tag{2} $$Pixels \(s\) and \(r\) are connected if there is a sequence of pixels from \(s\) to \(r\) in which each pixel is a connected neighbor of the one before it. The connected set of a seed \(s_0\) is the set of all pixels connected to it. A connected component is a set that is the connected set of each of its pixels.
The connected set may be found by maintaining 1) a list of pixels \(B\) which are known to be connected to \(s_0\) but have not yet been searched, and 2) a segmentation image \(Y\) which marks the pixels known to be connected to \(s_0\).
This type of algorithm is referred to as region growing, because the segmented region grows out from the seed point \(s_0\). At each step, \(B\) contains pixels at the boundary of the set whose neighbors have not yet been checked. A pixel is labeled when it enters \(B\), so it enters \(B\) at most once.
def connected_set(x, seed, T, label, seg):
"""Set seg = label at every pixel connected to seed; return the pixel count.
x (H, W) uint8 NumPy array
seed (row, col) of the seed pixel
T int, the threshold in gray levels
label int > 0, the label written into seg
seg (H, W) int32 NumPy array, changed in place
returns int, the number of pixels connected to the seed
"""
Requirements:
seg already equals
label counts as found.int before
subtracting. In uint8, \(3 - 5\) gives 254.seg to
label. Otherwise leave its value unchanged.
Task 3a. Display img22g.png in grayscale with a
colorbar and labeled axes.
Task 3b. For \(T = 1\), \(2\), and \(3\), start from
seg = np.zeros(x.shape, dtype=np.int32), run
connected_set with seed \((m, n) = (90, 134)\) and
label 1, and report the pixel count. Save the set in black on white:
save_image(np.where(seg == 1, 0, 255).astype(np.uint8), path).
Task 3c. Check by hand. Print x[88:93, 132:137],
the \(5 \times 5\) block centered on the seed. Find by hand which
neighbors of the seed are connected neighbors for \(T = 1\), and
confirm that this agrees with Task 3b.
img22g.png, the three connected set images, the three
pixel counts, and your check by hand.
Extract all the connected sets by indexing through the image in raster
order and applying connected_set, with the next unused
label, at each pixel that does not yet belong to a connected set. Then
generate a segmentation consisting of the connected sets with more
than 100 pixels. Number each of these large connected sets
sequentially starting at 1, in scan order. Label all remaining pixels
0. The relabeling may use NumPy array operations.
def segment(x, T, min_size, connected_set_fn):
"""Label connected components; keep those with more than min_size pixels.
x (H, W) uint8 NumPy array
T int, the threshold in gray levels
min_size int, a component is kept if it has more than min_size pixels
connected_set_fn connected_set or connected_set_c
returns (labels, K, n_all): (H, W) int32 label array, the number
of kept components, and the number of all components
"""
Task 4a. For \(T = 1\), \(2\), and \(3\), run
segment(x, T, 100, connected_set). Report the number of
all components and of kept components. Save each label image with
save_label_image.
Task 4b. Time each segmentation with
time.perf_counter(), smallest of 3 runs. Report your
computer model.
The three color label images, a table of all and kept component counts for each \(T\), and the three Python times.
Check whether the shell finds a compiler named cc:
cc --version
If not, install one:
xcode-select --install (Apple's Command
Line Tools, with clang).sudo apt update && sudo apt install build-essential.conda install -n labs -c conda-forge c-compiler, then
conda deactivate and
conda activate labs.connect.c
Direct your AI assistant to write these two functions.
connected_set is the algorithm of Step 3.
segment_image produces the same label image as
segment in Step 4, entirely in C.
#include <stdlib.h>
/* Label every pixel connected to the seed; pixel (m, n) is element m*W + n.
* Returns the number of pixels labeled, or -1 if memory allocation fails.
*/
int connected_set(const unsigned char *x, int height, int width,
int seed_row, int seed_col, int T, int label, int *seg)
{
}
/* Segment the image in one call; kept components get labels 1 to K, others 0.
* Stores the number of all components in *n_all. Returns K, or -1 if
* memory allocation fails.
*/
int segment_image(const unsigned char *x, int height, int width, int T,
int min_size, int *labels, int *n_all)
{
}
Requirements:
static helper that
both functions call and that takes the list of unsearched pixels as
an argument.int array from malloc,
freed before the public function returns.
segment_image allocates it once for all
components.m*width + n.exit.
Compile a shared library in the folder that holds
lab5.py (Mac, Linux, or WSL):
cc -O2 -shared -fPIC -o libconnect.so connect.c
-O2 turns on optimization, -shared builds a
library instead of a program, and -fPIC makes code that a
shared library needs. Do not commit libconnect.so.
Copy these functions into lab5.py. They use
ctypes to call the library.
connected_set_c has the same signature as
connected_set, and segment_c returns the
same values as segment.
_LIB = None
def load_connect_library(path=None):
"""Load libconnect.so (default: next to this file) once and declare its argument types."""
global _LIB
if _LIB is None:
if path is None:
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "libconnect.so")
lib = ctypes.CDLL(path)
lib.connected_set.restype = ctypes.c_int
lib.connected_set.argtypes = [
ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_void_p]
lib.segment_image.restype = ctypes.c_int
lib.segment_image.argtypes = [
ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)]
_LIB = lib
return _LIB
def connected_set_c(x, seed, T, label, seg):
"""Same as connected_set, using C; x is C-contiguous uint8, seg C-contiguous int32."""
if x.dtype != np.uint8 or seg.dtype != np.int32 \
or not x.flags.c_contiguous or not seg.flags.c_contiguous \
or x.shape != seg.shape:
raise TypeError("x must be C-contiguous uint8 and seg C-contiguous int32 of the same shape")
lib = load_connect_library()
H, W = x.shape
count = lib.connected_set(x.ctypes.data, H, W, int(seed[0]), int(seed[1]),
int(T), int(label), seg.ctypes.data)
if count < 0:
raise MemoryError("connected_set in C could not allocate its list")
return count
def segment_c(x, T, min_size):
"""Same as segment(x, T, min_size, connected_set_fn), in one call to C."""
if x.dtype != np.uint8 or not x.flags.c_contiguous:
raise TypeError("x must be a C-contiguous uint8 array")
lib = load_connect_library()
H, W = x.shape
labels = np.empty((H, W), dtype=np.int32)
n_all = ctypes.c_int(0)
K = lib.segment_image(x.ctypes.data, H, W, int(T), int(min_size),
labels.ctypes.data, ctypes.byref(n_all))
if K < 0:
raise MemoryError("segment_image in C could not allocate its arrays")
return labels, K, n_all.value
C receives only the address x.ctypes.data, not the shape
or type. The wrappers check them, because a wrong type or
non-contiguous array makes C read the wrong bytes with no error.
Task 8a. Repeat Task 3b with connected_set_c. For
each \(T\), report the pixel count and the number of pixels where the
label images differ.
Task 8b. Repeat Task 4a with
segment(x, T, 100, connected_set_c). Report the two
component counts and the number of differing pixels.
Task 8c. Repeat Task 4a with segment_c(x, T, 100).
Report the two component counts and the number of pixels that differ
from Task 4a.
A table, for each \(T\), of differing pixels for the connected set and the two C segmentations, and the component counts of both C segmentations.
Call load_connect_library() before timing. Start every run
from a new array of zeros for seg.
Task 9a. Time connected_set and
connected_set_c on seed \((90, 134)\) with \(T = 2\),
smallest of 5 runs.
Task 9b. For \(T = 1\), \(2\), and \(3\), time
segment with connected_set,
segment with connected_set_c, and
segment_c, smallest of 3 runs.
Task 9c. Report the speedup of each C version: Python time divided by C time.
A table of times and speedups for the connected set and for the three segmentations at each \(T\).
Read connect.c until you can explain every line. Ask the
AI about lines you do not understand, but write the explanation
yourself. Answer these questions:
uint8 and int32?segment_image track
component sizes and renumber the kept components 1 to K?
Your explanation of the four topics, in your own words, citing lines
of connect.c by number.
You directed your AI assistant to write four functions:
connected_set and segment in Python, and
connected_set and segment_image in C.
The specification you gave your AI assistant, quoted, with any corrections and what was wrong.
Answer each in a few sentences. Cite your own images and numbers.
connected_set_c only
a little faster than pure Python, while segment_c is
much faster? Time 10000 calls of connected_set_c on a
one-pixel component, compute the time per call, multiply by the
number of components from D2, and compare with the loop time. What
does segment_c avoid?skimage.measure.label labels components of equal
values. Which \(T\) makes our problem the same? Run
skimage.measure.label(x, connectivity=1, background=-1)
and segment_c with that \(T\), and compare component
counts and run times.Your answers to the seven questions.
Submit three files through Brightspace:
lab5.py, as a plain .py file.connect.c, as a plain .c file.
Do not paste code into the report, send a zip file, or send
libconnect.so. Commit and push lab5.py and
connect.c to your image-processing-labs
repository under lab5 before you submit.
img22g.png, the three connected set images, the three
pixel counts, and your check by hand.Concise and clear beats long.