Color detection in python : Opencv



 Color Detection in Python :







Hello and thanks for taking some time to read up my blog today. I recently learned and made a color detection program which works with a python library called 'OpenCV'. OpenCV stands for 'Computer Vision'. We could use this program to build a color tracking robot , the step needed to make this color detection code are the same in my last published blog (Face Tracking Device : Python & Arduino ) you can have a look at it : https://creat-ly.blogspot.com/2022/02/tracking-device-python-arduino-hello.html




Supplies :

1. Installing Python
2. Installing OpenCV and numpy

Step 1: Installing Software supplies :


You can download python from : https://www.python.org/downloads/
Once you're done with the installation, open up your command prompt and type the following:
 
pip install opencv-python

This command will install both libraries needed : opencv and numpy

The following are the steps which will help you to build a real-time opencv application in python.




Step 3: Coding in Python:


Main code : 

    import cv2 as cv
    import numpy as np

    cap = cv.VideoCapture(0)


    while True :

        s,img = cap.read()
   
        low = np.array([90, 80, 100])
        dark = np.array([130, 255, 255])

        hsv = cv.cvtColor(img,cv.COLOR_BGR2HSV)
        mask = cv.inRange(hsv,low,dark)
        save = cv.bitwise_and(img,img,mask=mask)

        contour, heirarchy = cv.findContours(mask,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_NONE)
        if len(contour) != 0:
            for i in contour :
                if cv.contourArea(i) >500 :
                    x,y,w,h = cv.boundingRect(i)
                    cv.rectangle(save,(x,y),(x+w,y+h),(0,255,0),3)
                    print (x,y,w,h)

        cv.imshow('video',save)

        if cv.waitKey(1) & 0xFF == ord('m'):
            break
    cap.release()
    cv.destroyAllWindows()

First of all we import the modules opencv and numpy by these two lines of code .

import cv2 as cv  
import numpy as np  

Videos shot with cameras are basically bunches of photos, so if we want to record a video we should make a while loop where we should write our code, then we should test if everything is good so we can store the "cap" variable in another varibale which we'll call "img".


    -    Defining the margin of the color we want to detect :

    low = np.array([90, 80, 100])
    dark = np.array([130, 255, 255])

these two variables ' low ' and 'dark' contain the values of the color we want to detect in HSV format .In my case I chosed to detect the blue color . it's up to you to chose whatever color you want to detect 

HSV is a cylindrical color model that remaps the RGB primary colors into dimensions that are easier for humans to understand. Like the Munsell Color System, these dimensions are hue, saturation, and value.

  • Hue specifies the angle of the color on the RGB color circle.
  • Saturation controls the amount of color used.
  • Value controls the brightness of the color.
The picture below shows how the HSV model looks like :

 


    -    Applying the mask on the picture :

hsv = cv.cvtColor(img,cv.COLOR_BGR2HSV)

To detect a color using open-cv we should convert the picture from BGR (Blue,Green,Red) to HSV(Hue,Saturation,Value) and we store it in " hsv " variable so we can apply the mask on the picture by using the next line .

mask = cv.inRange(hsv,low,dark)

Here we defining the range of the lowest and the darkest color we want to detect in the ' hsv ' picture .

save = cv.bitwise_and(img,img,mask=mask)

After all this steps, we define a variable called "save" where we store the result of the original image applied to the mask by the function "bitwise_and"  by specifying the two input images ("img" and "mask") as the parameters which returns the merged image as the resulting image displayed as the output on the screen. 


    -    Drawing the contours on the  detected color :

            contour, heirarchy = cv.findContours(mask,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_NONE)                  
            if len(contour) != 0:                                                                            
                for i in contour :                                                                            
                    if cv.contourArea(i) >500 :                                                              
                        x,y,w,h = cv.boundingRect(i)                                                          
                        cv.rectangle(save,(x,y),(x+w,y+h),(0,255,0),3)                                        
                        print (x,y,w,h)                                                                      

Opencv offers the possibility to draw contours on different shapes , there are a lot of type of contours and
a lot of functions to use for each application, I'll leave the documentation of contours hierarchy provided by openCV
I really recomand you to take a look at it .



After setting the contour we should display the video in a window using the next line of code 

cv.imshow('video',save)

This function has two parameters, 'video ' and that refers to the name of the window
and 'save' which is the variable where the result of the mask that is applied to the picture

        if cv.waitKey(1) & 0xFF == ord('m'):
            break
    cap.release()
    cv.destroyAllWindows()

Finally we should define the key that closes the window if we want to, in my case I chose the key 'm' then if the window is closed we should deallocates its memory .

 The result of my code : 





Articles les plus consultés