Color detection

In computer vision, colour detection is a process of identifying and analysing colors within digital images or video streams. It’s a fundamental task in many computer vision applications, including object recognition, image segmentation, and tracking.


In this example, we will detect the number of cylinders of a specific color in the image and count them. This is the image that we will use:

Each one of the colours is defined, so we can select which color we want to detect and apply some filters in order to count the number of corresponding cylinders.


(libraries to install):

pip install numpy
pip install cv2
pip install argparse


Inside the CMD folder, you can execute the program. You can determine which colour you want to detect by using the following:

python -c {red, orange, yellow, green, blue, purple}

For example, if you want to detect the green circles, execute:

python -c green

The image is then filtered with a median and a Gaussian filter and converted to HSV colour space. After that, a colour mask applies to detect the cylinders with the colour that you selected. The colour range used depends on the colour that you chose. If you chose green, then the colour ranges are:

upper_range=(75, 255, 255)

Over this colour mask, an open morphological operation is applied in order to clean the detections, obtaining a mask that looks like this:

Then, we find the contours from the previous mask and filter them by a minimum area. We then draw the minimum enclosing circle of each contour, wrapping the detection. For each detection, weassign a number to it and arrive at the total number of detections of green cylinders.


To receive the “Color detection” code, please fill out the form below.

Upon submission, we’ll promptly send you the ZIP file containing the code you requested. Please ensure you’ve checked your spam folder if you don’t receive our email shortly after submitting your request.