Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 54 ยท Practice and Review

Practice Exercises with Solutions

Practice OpenCV ideas with 12 graded exercises on pixels, color, thresholds, filters, edges and contours. Every solution is a numpy stand-in you can run and edit.

Reading about computer vision teaches you the vocabulary; solving small problems teaches you to see images as arrays. This page has 12 exercises, ordered from easy to challenging. Each one states a task, then gives a runnable solution with assert statements, so a wrong edit fails loudly instead of printing something that merely looks plausible.

An honest note on what runs here: the cv2 module cannot run on this site. Every solution below uses numpy to rebuild what the matching OpenCV function does, so you practice the idea and the array shapes, not the library call. For each exercise the text names the OpenCV function you would use in a real project. The images are tiny and synthetic, so every run is identical.

How to use this page

Do not run the solution first. Read the task, write your own answer in a scratch editor (or delete the body of the solution and type yours), and compare your output with the assertions. If an exercise takes you more than ten minutes, peek, then close the solution and redo it from memory the next day.

A routine for every exercise

Shapes first Write down (H, W, C) and the dtype of every input.
Tiny example Print a 5 by 5 case and check it by hand.
Whole arrays Prefer slices, masks and axis over pixel loops.
Assert it Turn your hand check into an assert.

Most OpenCV bugs are shape, dtype or channel-order bugs.

1 / 2

Part 1: Pixels and arrays

Related lessons: Images Are NumPy Arrays and Accessing and Modifying Pixels.

Exercise 1 (easy). Create a grayscale image of 6 rows and 8 columns where the pixel in column c has the value c * 36, stored as uint8. Print its shape and dtype, and read the pixel at row 2, column 5.

Python Exercise 1: a gradient image

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). On an 8 by 12 black image, draw a filled white rectangle whose top-left corner is at x=3, y=2 and whose bottom-right corner is at x=8, y=5, inclusive (the way cv2.rectangle treats both corners). Count the white pixels.

Python Exercise 2: a filled rectangle by slicing

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). Given a 2 by 2 BGR image, produce the RGB version and a grayscale version using the weights 0.299 (red), 0.587 (green) and 0.114 (blue), rounded to uint8. Remember that OpenCV stores channels in B, G, R order.

Python Exercise 3: BGR to RGB and 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.

Part 2: Color and data types

Related lessons: Color Spaces and Data Types, Ranges and Saturation.

Exercise 4 (easy). Remove all red from a BGR image so only blue and green remain. Do it without modifying the original array.

Python Exercise 4: zero one channel

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). Brighten a grayscale image by 100 in two ways: plain uint8 addition (what img + 100 does in numpy) and saturating addition (what cv2.add does). Show that the first wraps around and the second clips at 255.

Python Exercise 5: wraparound versus saturation

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: Thresholds and masks

Related lessons: Thresholding and Arithmetic, Bitwise Ops and Masking.

Exercise 6 (easy). Apply a binary threshold of 127 (cv2.THRESH_BINARY) and the inverted version. Check that the strict "greater than" rule sends the value 127 to 0 in the normal mode.

Python Exercise 6: binary and inverted

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 7 (medium). Build a mask of the "reddish" pixels in a BGR image: blue at most 80, green at most 80, red at least 150 (this is what cv2.inRange computes with a lower and an upper bound per channel). Then use the mask to keep only those pixels and make everything else black.

Python Exercise 7: inRange and masking

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). Compute the 256-bin histogram of a small grayscale image with np.bincount, find the most common value, and stretch the contrast so the minimum maps to 0 and the maximum to 255 (the idea behind cv2.normalize with NORM_MINMAX).

Python Exercise 8: histogram and 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.

Part 4: Filters and edges

Related lessons: Blurring and Noise Reduction, Kernels and filter2D, Gradients, Sobel and Laplacian and Morphological Operations.

Exercise 9 (medium). Apply a 3 by 3 box blur to the interior of a 5 by 5 image that contains a single bright pixel in the middle. Compute each output pixel as the mean of its 3 by 3 neighborhood, without Python loops over pixels (shift and add slices).

Python Exercise 9: a box blur with shifted slices

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 10 (hard). Compute the horizontal Sobel response Gx for the interior of an image that has a vertical step edge (left half 0, right half 100). Use the kernel [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] and show that the response is large only next to the edge.

Python Exercise 10: Sobel on a step 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.

Exercise 11 (hard). Remove an isolated noise pixel from a binary image with an opening: erosion followed by dilation, both with a 3 by 3 square. The big square blob must survive and the lone pixel must vanish.

Python Exercise 11: opening removes specks

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: Contours

Related lessons: Finding and Drawing Contours and Contour Features.

Exercise 12 (hard). Label the connected blobs in a small binary image (4-connectivity) and report each blob's area and bounding box as (x, y, w, h). This is the same information you would collect from cv2.findContours, cv2.contourArea and cv2.boundingRect, here found with a flood fill instead.

Python Exercise 12: blobs, areas and 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.

Where to go from here

Redo the exercises you found hard with a different image. Try the Sobel exercise on a horizontal edge, or erode with a 5 by 5 square and see how the blob shrinks. If you want deeper practice, rebuild one of the projects from scratch, then move on to interview questions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In exercise 2, why does the slice use y2 + 1 and x2 + 1?

    A numpy slice stops before its end index, while cv2.rectangle draws through both corner pixels, so the slice end needs +1 to match.
  2. 2. Which statement about uint8 arithmetic is correct?

    numpy keeps the dtype and wraps around (250 + 100 becomes 94), while cv2.add saturates (250 + 100 becomes 255).
  3. 3. After a morphological opening, what happens to a one-pixel speck of noise?

    Erosion removes any foreground shape smaller than the structuring element. Dilation afterwards restores only what survived.
  4. 4. Why does the Sobel response in exercise 10 stay 0 in the flat regions?

    The Sobel x kernel's weights add up to 0, so equal pixels on both sides cancel. Only a change in brightness produces a nonzero response.

Summary

  • Rows come first in indexing (img[y, x]), and numpy slices exclude the end index.
  • OpenCV stores color as B, G, R, so channel index 2 is red.
  • uint8 numpy math wraps; cv2.add saturates. Convert to a wider type, compute, then clip when you want saturation.
  • Thresholds use a strict "greater than", masks are boolean arrays, and np.where applies them.
  • Box blur, Sobel and morphology are all "shift the array and combine" operations, so no pixel loops are needed.
  • Connected blobs give you areas and bounding boxes, the same facts a contour pipeline reports.

Next up: OpenCV Interview Questions.