ECE 63700: Digital Image Processing I

Lab 5: Neighborhoods and Connected Components

Overview What the lab is about, the data, and the ground rules.

What This Lab Is About

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.

The Data

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

Ground Rules

  • Python code goes in 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.
  • Use the exact signatures on this page, each with a short docstring.
  • Gray levels are integers from 0 to 255. Read the image as uint8 and do not scale it. The thresholds \(T = 1, 2, 3\) are in gray levels.
  • Pixel \((m, n)\) is row \(m\), column \(n\). The upper left pixel is \((0, 0)\).
  • connected_set in Module 1 is pure Python, with no vectorized NumPy operations.
Give the AI the definitions, array types and shapes, index convention, algorithm, and signatures. For C, also give the prototypes and the memory layout. Run the checks in Steps 3 and 8 before you interpret any image.
Parameters for the Experiments The settings for every hand-in item.

Parameters for Every Experiment

ItemExperimentInputFunction and settings
D1Connected set of the seed (Step 3) img22g.png connected_set, seed \((m, n) = (90, 134)\), \(T = 1, 2, 3\), label 1, 4-point neighborhood
D2Segmentation in Python (Step 4) img22g.png segment with connected_set, \(T = 1, 2, 3\), keep components with more than 100 pixels
D3C 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
D4Timings (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
D5How the C code works (Step 10) connect.c —
Module 1: Region Growing in Python Steps 1 to 4. Set up the code, define connected pixels, grow a connected set from a seed, and segment the whole image.

Step 1: Set Up 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)

Step 2: Neighborhoods and Connected Sets

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\).

Region growing from the seed \(s_0\).
  1. Set \(Y_{s_0} \leftarrow\) label and \(B \leftarrow \{s_0\}\).
  2. While \(B\) is not empty:
    1. Remove any pixel \(s\) from \(B\).
    2. For each \(r \in c(s)\) whose \(Y_r\) is not yet the label, set \(Y_r \leftarrow\) label and add \(r\) to \(B\).

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.

Step 3: Grow the Connected Set of a Seed

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:

  • Follow Step 2 with an explicit Python list of unsearched pixels, not recursion. A pixel whose seg already equals label counts as found.
  • Read and write the arrays one element at a time. Do not convert the whole image, because Step 4 calls this function once per component.
  • Convert gray levels to Python int before subtracting. In uint8, \(3 - 5\) gives 254.
  • If a pixel is connected to the seed, set its 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.

HAND IN · D1

img22g.png, the three connected set images, the three pixel counts, and your check by hand.

Step 4: Segment the Whole Image

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.

HAND IN · D2

The three color label images, a table of all and kept component counts for each \(T\), and the three Python times.

Module 2: Region Growing in C Steps 5 to 12. Get a compiler, write connected_set and segment_image in C, call them from Python, check them, time them, explain them, and answer the questions.

Step 5: Get a C Compiler

Check whether the shell finds a compiler named cc:

cc --version

If not, install one:

  • Mac: xcode-select --install (Apple's Command Line Tools, with clang).
  • Linux or WSL (Ubuntu): sudo apt update && sudo apt install build-essential.
  • conda: conda install -n labs -c conda-forge c-compiler, then conda deactivate and conda activate labs.

Step 6: Write 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:

  • Write the region growing once, in a static helper that both functions call and that takes the list of unsearched pixels as an argument.
  • The list is an int array from malloc, freed before the public function returns. segment_image allocates it once for all components.
  • The list stores each pixel as m*width + n.
  • The list holds every pixel of the image, so it cannot overflow. Explain in D5 why that size is enough.
  • The functions do not print, read files, or call 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.

Step 7: Call the C Function from Python

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.

Step 8: Check C Against Python

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.

Pass criterion. Every difference count is exactly 0, and every count matches Module 1. Any nonzero difference is a bug.
HAND IN · D3

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.

Step 9: Time Both Versions

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.

HAND IN · D4

A table of times and speedups for the connected set and for the three segmentations at each \(T\).

Step 10: Read and Explain the C Code

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:

  • Arrays and indexing. How does the code find the gray level of pixel \((m, n)\)? Why must the arrays be C-contiguous uint8 and int32?
  • Memory allocation. What does each function allocate, how large, and where is it freed? Why can the list never overflow? Which memory belongs to NumPy, and why must C never free it?
  • The list of unsearched pixels. How are pixels added and removed, and in what order do they leave? How are \(m\) and \(n\) recovered from the index? How are neighbors outside the image skipped?
  • The segmentation. How does segment_image track component sizes and renumber the kept components 1 to K?
HAND IN · D5

Your explanation of the four topics, in your own words, citing lines of connect.c by number.

Step 11: Your Specification

You directed your AI assistant to write four functions: connected_set and segment in Python, and connected_set and segment_image in C.

HAND IN · D6

The specification you gave your AI assistant, quoted, with any corrections and what was wrong.

Step 12: Questions to Answer

Answer each in a few sentences. Cite your own images and numbers.

  1. In Labs 3 and 4, one array operation computed every output pixel. Why can region growing not be written that way? What does each step depend on?
  2. Why does C grow the region of Task 9a so much faster than Python? What does the interpreter do per pixel that compiled C does not?
  3. Why is the Python loop that calls 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?
  4. How do the seed's set size, the number of all components, and the number of kept components change as \(T\) goes from 1 to 3? Why does the number of kept components not simply rise or fall? Use D1 and D2.
  5. With the 8-point neighborhood, which adds the four diagonals, can a connected set get smaller? Can the number of components get larger? What new way of crossing a boundary does it allow? You may test this in a copy of your code.
  6. 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.
  7. Based on your timings and Question 6, when is it worth writing C code today?
HAND IN · D7

Your answers to the seven questions.

Deliverables What to submit, and where each item comes from.

What to Hand In

Submit three files through Brightspace:

  1. A report, as a single PDF, labeled "Lab 5", with the items below in this order.
  2. Your lab5.py, as a plain .py file.
  3. Your 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.

  1. Your name and the link to your GitHub repository.
  2. D1 img22g.png, the three connected set images, the three pixel counts, and your check by hand.
  3. D2 The three color label images, the component counts, and the Python segmentation times.
  4. D3 The table comparing the two C versions with Python: differing pixels and component counts.
  5. D4 The table of times and speedups for the three versions.
  6. D5 Your explanation of the C code: arrays and indexing, memory allocation, the list of unsearched pixels, and the segmentation.
  7. D6 The specification you gave your AI assistant, quoted, with any corrections.
  8. D7 Your answers to the seven questions.

Concise and clear beats long.