Color segmentation is very useful in many classic image analysis tasks. This is
a simple real-world example of how color information can be used to find objects
in an image. The following code is based on this great
tutorial that you should
definitely check out!
The task is to segment pills from images like the one shown below.
The test image used in this example can be downloaded from this
link.
The following code converts the image to HSV space and transforms the pixel
values (e.g. normalization) to make them easier to plot. It’s usually better to
plot the color data using a script run from the terminal. This allows rotating
the 3D plot and facilitates the task of finding value ranges for the target
colors. A color_plot script is available in the
twoisprime package.
Finding the appropriate color ranges is a trial and error process with this
method. I have looked into clustering ideas but it doesn’t seem to be
straightforward. Please let me know if you have any tips!
The following three cells show the segmentation obtained for blue, brown
(yellow), and red:
Finally we can get the pill contours filtering by area. Calculating the convex
hull makes the result look cleaner. Very simple and effective!