Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 46 ยท Practice and Review

Practice Exercises with Solutions

Practice computer vision with 18 graded exercises on arrays, filters, thresholds, features, segmentation and metrics. Every solution runs live in your browser.

Reading about image processing teaches you the vocabulary; solving small problems teaches you to see images as arrays. This page has 18 exercises, ordered from easy to challenging and grouped by topic. Each one states a task and then gives a runnable solution. The solutions use assert, so if you edit the code and break it, the run fails loudly, and they print what they computed so you can compare with your own answer.

For the best learning, do not run the solution first. Read the task, write your own code in a scratch editor, and only then compare. Everything uses tiny synthetic images, so you can print and inspect every number.

How to attack an image problem

  1. Write the shape and dtype first. Is it (H, W) or (H, W, 3)? uint8 or float? Most bugs live here.
  2. Prefer whole-array expressions (slices, masks, axis=) over pixel loops, except when the loop is the lesson, as in convolution.
  3. Print a tiny case and check it by hand before trusting the code on a big image.
flowchart TD
    A["Read the task"] --> B["Write input and<br/>output shape and dtype"]
    B --> C{"What kind of step?"}
    C -- "pixel values" --> D["Masks, clip, where"]
    C -- "neighbourhoods" --> E["Convolution, filters,<br/>morphology"]
    C -- "regions" --> F["Label, measure,<br/>compare masks"]
    D --> G["Print a small example<br/>and check by hand"]
    E --> G
    F --> G

A routine that works for almost every exercise below.

Part 1: Arrays and color

Related lessons: Images as Arrays and Color Channels and Color Spaces.

Exercise 1 (easy). Build a uint8 grayscale image with 6 rows and 8 columns where each column's value is column_index * 32. Print its shape and dtype, then crop the central 2 by 4 block (rows 2 to 3, columns 2 to 5).

Python Exercise 1: gradient and crop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 2 (easy). Make a 2 by 2 RGB image with pixels red, green, blue and white (as uint8). Swap the red and blue channels to produce a BGR copy, and compute the luminance gray image with the weights 0.299, 0.587, 0.114.

Python Exercise 2: swap channels, make gray

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 3 (medium). A uint8 image has the values [10, 120, 200, 250]. Add 100 to every pixel without wrapping around past 255. Show what the naive img + 100 gives, then fix it.

Python Exercise 3: no overflow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Part 2: Filters and edges

Related lessons: Convolution and Correlation, Blurring and Denoising and Gradients and Edge Detection.

Exercise 4 (medium). Write a function box_blur(img) that replaces each interior pixel of a 2D float array by the mean of its 3 by 3 neighbourhood, using loops, and leaves the border unchanged. Check it against scipy.ndimage.uniform_filter on the interior.

Python Exercise 4: box blur from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 5 (medium). Take a flat gray image (value 100) and set 5 pixels to 255 (salt noise). Show that a 3 by 3 median filter removes all of them while a 3 by 3 box filter only smears them.

Python Exercise 5: median beats box on salt noise

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 6 (medium). Build a 8 by 8 image whose left four columns are 0 and right four columns are 200. Compute the horizontal gradient with the Sobel kernel and find which columns respond. Verify that the vertical gradient is zero in the interior.

Python Exercise 6: find a vertical edge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Part 3: Histograms and thresholds

Related lessons: Histograms and Equalization and Thresholding.

Exercise 7 (easy). For the image [[0, 0, 1], [1, 2, 2]] (values 0 to 3) compute the histogram with four bins and the cumulative distribution (cumulative sum divided by the pixel count).

Python Exercise 7: histogram and CDF

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 8 (medium). A low-contrast image uses only the values 100 to 140. Stretch it linearly so the minimum becomes 0 and the maximum 255 (as uint8).

Python Exercise 8: contrast stretch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 9 (medium). Write otsu(gray) that returns the threshold maximizing the between-class variance (test thresholds 1 to 255, using img >= t for the bright class). Check it on an image with two flat plateaus, 50 and 180, plus a little noise: the result must lie strictly between the plateaus.

Python Exercise 9: Otsu

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Part 4: Features and matching

Related lessons: Corner Detection, Template Matching and Hand-Crafted Features and HOG.

Exercise 10 (medium). Compute the dominant gradient direction of a patch that is a ramp increasing to the right. Report the angle in degrees using np.gradient and np.arctan2; it should be 0 (the gradient points to the right).

Python Exercise 10: gradient direction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 11 (medium). Hide a 3 by 3 pattern inside a 10 by 10 noisy image at a known position. Find its location by sliding the template and minimizing the sum of squared differences (SSD).

Python Exercise 11: find the patch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 12 (hard). Compute a normalized 4-bin color-intensity histogram for two images and compare them with the histogram intersection (sum of the element-wise minimum). A dark image compared with itself must score 1; compared with a bright image it must score 0.

Python Exercise 12: histogram similarity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Part 5: Segmentation and shapes

Related lessons: Morphological Operations, Connected Components and Labeling and Contours and Shape Measurements.

Exercise 13 (easy). Count the objects in a binary mask with scipy.ndimage.label, first with 4-connectivity (the default) and then 8-connectivity. The mask has two blobs that touch only diagonally.

Python Exercise 13: 4 versus 8 connectivity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 14 (medium). Remove speckles from a mask with a morphological opening. The mask holds one 5 by 5 square and three isolated single pixels. After opening with a 3 by 3 structuring element, only the square must remain.

Python Exercise 14: clean a mask

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 15 (medium). Label a mask with three blobs and build a small table with each blob's area, centroid (row, column) and bounding box. Report the largest blob.

Python Exercise 15: measure the blobs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Part 6: Metrics and evaluation

Related lessons: Object Detection Basics, Semantic Segmentation and Its Metrics and Evaluating Vision Models.

Exercise 16 (easy). Write iou(a, b) for boxes given as (x1, y1, x2, y2) with x2 > x1 and y2 > y1. Test: identical boxes give 1, disjoint boxes give 0, and (0, 0, 4, 4) with (2, 2, 6, 6) gives 4 / 28.

Python Exercise 16: IoU of boxes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 17 (medium). Implement greedy non-maximum suppression. Given boxes with scores, keep the highest-scoring box, drop every remaining box whose IoU with it exceeds 0.5, and repeat. Three boxes overlap heavily around one object and a fourth box sits elsewhere; two boxes must survive.

Python Exercise 17: non-maximum suppression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 18 (hard). For two label masks, truth and pred (0 = background, 1 = object), compute pixel accuracy, IoU and the Dice coefficient. Then show why pixel accuracy is misleading when the object is small.

Python Exercise 18: segmentation scores

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last assertion is the lesson: an empty prediction also reaches 96% pixel accuracy, while IoU and Dice reveal that the object was barely found.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A uint8 pixel holds 250. What does img + 10 produce for that pixel when both operands are uint8?

    uint8 arithmetic wraps modulo 256, so 250 + 10 becomes 4. Convert to a wider type and clip to saturate at 255.
  2. 2. Which filter removes isolated salt-and-pepper pixels without smearing them into their neighbours?

    The median ignores extreme values in the window, so a lone outlier disappears. A box filter averages it into the surroundings.
  3. 3. Why is pixel accuracy a poor metric for segmenting a small object?

    When the object covers few pixels, the background dominates the count. IoU and Dice focus on the object itself.
  4. 4. In greedy non-maximum suppression, what happens to a box that overlaps a higher-scoring kept box with IoU above the threshold?

    NMS treats such a box as a duplicate detection of the same object and drops it.

Summary

  • Check shape and dtype first; uint8 arithmetic wraps, so widen and clip.
  • Filters: a box blur averages, a median removes outliers, Sobel measures change along one axis.
  • Otsu maximizes between-class variance; a contrast stretch rescales the min and max to 0 and 255.
  • Template matching slides a patch and minimizes SSD; histogram intersection compares distributions.
  • ndi.label counts blobs (connectivity matters), opening removes speckles, and ndi.sum / center_of_mass / find_objects measure them.
  • IoU and Dice describe overlap, NMS removes duplicate boxes, and pixel accuracy hides failures on small objects.

Next up: rehearse explaining these ideas in Computer Vision Interview Questions.