Change language

Detecting a specific color (blue here) using OpenCV with Python

| | | |

The following python code uses the OpenCV library, which is used for image processing techniques. The program allows you to detect a specific color in live video content. The video consists of endless frames at different points in time. We will define the color of each frame one by one. 
The code will only compile on Linux.
Make sure openCV is installed on your system before running the program. 
To install:

  • Run the following command on your terminal to install from Ubuntu or Debian repository.
     sudo apt-get install libopencv- dev python-opencv 
  • OR To download OpenCV from the official site, run the following command:

    on your terminal. Enter your sudo password and you will have OpenCV installed. 
    This operation can take a long time due to the packages being installed and the compilation process.

  • To install numpy, simply use the command:
     sudo pip install numpy 

# Python detection tool
# specific color (blue here) with using OpenCV with Python

import cv2

import numpy as np 

# Webcam # 0 is used to capture frames

cap = cv2.VideoCapture ( 0

# This puts the program in an endless loop.

while ( 1 ): 

# Captures live stream frame by frame

  _, frame = () 

# Converts images from BGR to HSV

hsv = cv2.cvtColor (frame, cv2.COLOR_BGR2HSV)

lower_red = np.array ([ 110 , 50 , 50 ])

upper_red = np.array ([ 130 , 255 , 255 ])

# Here we define a blue range in HSV
# This creates a blue mask
# objects found in the frame.

mask = cv2.inRange (hsv, lower_red, upper_red)

# Bitmap and frame and mask are done like this
# that only blue objects are highlighted
# and stored in Res

res = cv2.bitwise_and (frame, frame, mask = mask)

cv2.imshow ( ’frame’ , frame)

cv2.imshow ( ’mask’ , mask)

cv2.imshow ( ’res’ , res)

# This displays a frame, mask
# and res that we created in 3 separate windows.

k = cv2.waitKey ( 5 ) & amp;  0xFF

if k = = 27 :


# Destroys all HighGUI windows.
cv2.destroyAllWindows ()

# release the captured frame
cap.release ()

Code explanation:

  • Camera settings: The device’s webcam is used to perform runtime operations. To capture video, we need to create a VideoCapture object. Its argument can be either the device index or the name of the video file. Device index — it’s just a number indicating which camera. Usually one camera is connected, so we just transmit 0. You can select the second camera by transmitting 1 and so on. After that, you can capture frame by frame. But in the end, don’t forget to free the captive. Moreover, if anyone wants to apply this color detection technique to any image, it can be done with a small change in the code that I will share later.
  • Frame grabber: infinite loop is used to ensure that the webcam captures frames in each case and is open during the entire course of the program. 
    After capturing the live stream frame by frame, we convert each frame in BGR (default) color space to HSV color space. There are over 150 color space conversion methods available in OpenCV. But we will only consider two of them that are most widely used: BGR to gray and BGR to HSV. To transform the color, we use the cv2.cvtColor (input_image, flag) function, where flag defines the type of transformation. For BGR to HSV, we use the cv2.COLOR_BGR2HSV flag. Now we know how to convert a BGR image to HSV, we can use this to extract a colored object. It is easier to represent color in HSV than RGB color space. 
    When specifying a range, we specified a blue range. Whereas, you can enter a range of any color you want.
  • Masking technique: The mask basically creates a specific area of ​​the image by following certain rules. Here we create a mask consisting of a blue object. After that, I used bitwise_and on the input image and the thresholded image so that only blue objects are selected and saved in res. 
    Then we display the frame, resolution and mask in 3 separate windows using the imshow function.
  • Frame display: Since imshow () is a HighGui function, waitKey must be called regularly to handle its event loop. 
    The waitKey () function waits for a key event to "delay" (here 5 milliseconds). If you don’t call waitKey, HighGui won’t be able to handle Windows events like redraw, resize, input event, etc. So just call it, even with a 1ms delay.
  • To summarize the process :
    1. Take each frame of the video.
    2. Convert each frame from BGR to HSV color space.
    3. HSV image threshold for blue range .

This article courtesy of Pratima Upadhyay . If you are as Python.Engineering and would like to contribute, you can also write an article using or by posting an article contribute @ See your article appearing on the Python.Engineering homepage and help other geeks.


Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method