Engee documentation
Notebook

RGB in HSV and thresholding

This example illustrates how converting RGB to HSV and using this representation helps simplify segmentation processes.

The implementation of this function starts by connecting the libraries.

In [ ]:
Pkg.add(["LinearAlgebra", "TestImages"])
In [ ]:
using Images, TestImages, LinearAlgebra

Let's load a test image.

In [ ]:
rgb_img = testimage("lighthouse")
Out[0]:
No description has been provided for this image

HSV (Hue, Saturation, Value) is a colour model in which colour coordinates are:

  1. Hue - colour tone, e.g. red, green or blue;
  2. Saturation - saturation, and the higher this parameter, the "cleaner" the colour;
  3. Value - the value of the colour.

Let's bring the original RGB image to HSV representation.

In [ ]:
hsv_img = HSV.(rgb_img);

Select the channels of the HSV image.

In [ ]:
channels = channelview(float.(hsv_img));

hue_img = channels[1,:,:];
value_img = channels[3,:,:];
saturation_img = channels[2,:,:];

Then a simple image segmentation can be efficiently performed by defining the threshold of HSV channels.

In [ ]:
mask = zeros(size(hue_img))
h, s, v = 80, 150, 150
for ind in eachindex(hue_img)
    if hue_img[ind] <= h && saturation_img[ind] <= s/255 && value_img[ind] <= v/255
        mask[ind] = 1
    end
end
binary_img = colorview(Gray, mask)
Out[0]:
No description has been provided for this image

The resulting binary image can be used as a mask for the original RGB image.

In [ ]:
segmented_img = mask .* rgb_img
hcat(rgb_img, binary_img, segmented_img)
Out[0]:
No description has been provided for this image

Conclusion

In this demonstration we have learnt how to convert RGB to HSV and how to use this representation to facilitate image segmentation processes.