This chapter focused on segmenting the foreground from the background of an image using thresholding.
For images with (semi) controlled lighting conditions, thresholding is an easy way to segment the object of interest from the background.
In fact, many computer vision applications apply smoothing followed by thresholding or edge detection as a form of object detection. As we’ll see in Chapter 11 on contours, this is how we detect and count the number of coins in an image.
Get more practice with threshold parameters
When first using the cv2.threshold
function, I suggest playing around with the type
variable used to control how an image is thresholded.
This is an important parameter and if you don’t obtain some practical experience with it, you might end up with unexpected results when you apply thresholding to your own images.
Because of this, I suggest reading through the Thresholding: Simple Image Segmentation using OpenCV tutorial on the PyImageSearch blog:
Apply the watershed algorithm
Thresholding an image to segment the foreground from the background is all well and good, but what happens if my foreground objects are “touching” or “overlapping” as in this example image:
We can easily apply thresholding to obtain the foreground coins, but they’ll appear as one large connected blob, like this:
What do we do now?
We apply the watershed algorithm, which allows us to segment each of the individual coins from the image.