How To Track any colour in opencv python

 How to track any color in opencv python

import cv2

import  numpy as np 

cap = cv2.VideoCapture(0) # take webcam as input 

while True:

    success , frame = cap.read() # read the image  and store in frame variable

 # success purpose here is to   verify whether it is gettting input or not 

    hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) # converting bgr to hsv

    l_l =np.array([170,150,50]) #lower limit of hsv

    u_l = np.array([180,255,255]) # upper limit of hsv

    mask = cv2.inRange(hsv,l_l,u_l)  # mask

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

    cv2.imshow("frame",frame)

    cv2.imshow("mask",mask)

    cv2.imshow("result",result)

    cv2.waitKey(5)

cv2.destroyAllWindows()





hsv graph


Now lets try to understand what is going on

here what we have done we have take web cam live footage as input and convert it into hsv format


Whole process:

  1. First, we have taken the input video from our webcam the reason we put 0 in cv2.VideoCapture(0) is that we are taking the video from the laptop ibuilt webcam if we are using another web cam then we will enter 1 or 2 depending upon webcam no.
  2. After that, we have applied loop condition because we are taking a video as input  
  3. success, frame here success the only purpose is to check whether we are getting input or not. All our video data is going into frame variable
  4. After that we can convert our video data from bgr format to hsv data .(Note: OpenCV use bgr(blue , green, red) as conventional input taking format)
  5. The reason we have convert bgr into hsv is explained in the video with details
  6. After that we have given lower and upper limit. In hsv you can define limits to detect a color in particular easily 
  7. After that we have applied a mask its to show those area which are in the limits
  8. We have applied bitwise operation so that we can see merge our actual input and mask to highlight particular colour we are interest with
  9. After that we have simply show our actual video , mask , result as output

Why HSV format?

OpenCv detect HSV format better for object and color detection . HSV format is easier to control and predicts its value once you are familiar watch the tutorial video you will see why we choose hsv format.We can define color range that we need to detect in hsv very easily 

As you have seen in the tutorial we have defined upper and lower limit of to detbtect red color . this gives a boundry region (shown at the end of the video tutorial) to detect color within the range


After that we have apply mask to show only those area which are within the range

after that we have applied bitwise_and so that we can highlight the colored region in the result


if you have any kind of doubt and query please comment





Post a Comment

0 Comments