OK, Let’s step a little further. Let’s programme your computer to detect colors. Now you know what are the prerequisites for this purpose.

 

Open a new file in IDLE. Import OpenCV and numpy libraries.

import cv2

import numpy as np

 

Then we use a camera (I used the webcam of my computer)

cap = cv2.VideoCapture(0)

 

Now we start looping.

while(cap.isOpened):

We read frame by frame and convert the color scheme of the frame BGR to HSV
_, frame = cap.read()

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

Next we defined the color we desire. For each color we should define a upper and lower limit of color we required as a numpy array. Following is what I have chosen to define the range of green color in HSV.
lower_green = np.array([65,60,60])
upper_green = np.array([80,255,255])

Our frame, the HSV image, is thresholded among upper and lower pixel ranges to get only green colors
mask = cv2.inRange(hsv, lower_green, upper_green)

Then we use a kernel to watch through the image, or the frame, and dilated to smooth the image. Please refer the OpenCV docs for further information. click here.

kernel = np.ones((5,5),’int’)
dilated = cv2.dilate(mask,kernel)

With the mask we created above we extracted the green color area from original image.

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

Then we thresholded the masked image and get the contours.

ret,thrshed = cv2.threshold(cv2.cvtColor(res,cv2.COLOR_BGR2GRAY),3,255,cv2.THRESH_BINARY)
contours,hier = cv2.findContours(thrshed,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

 

We start a “for” loop to search through all the contours and get the area of each.

for cnt in contours:
area = cv2.contourArea(cnt)

It is not necessary to watch for all the contour areas because much smaller ones are annoying. Hence,  we define a minimum limit for the area. Here I will take any area over 1000. If an area over 1000 is detected then we put a text on the frame and  draw a rectangle around it.
if area >1000:
cv2.putText(frame, “Green Object Detected”, (10,80), cv2.FONT_HERSHEY_SIMPLEX, 1, 1)
cv2.rectangle(frame,(5,40),(400,100),(0,255,255),2)

 

We can now watch what happening on the screen.

cv2.imshow(‘frame’,frame)

 

We break the loop as before using ESC key.

k = cv2.waitKey(5) & 0xFF
if k == 27:
break

 

It is better to release the video capture.

cap.release()
cv2.destroyAllWindows()

Save the file. Run —> Run Module Or hit F5. Download the python script Here.







Detect a Green Color Object with OpenCV

Leave a Reply

Your email address will not be published. Required fields are marked *