SunFounder picar-x
(continued from previous page)
# Find the contour in morphologyEx_img, and the contours are arranged according
˓→to the area from small to large.
_tuple = cv2.findContours(morphologyEx_img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_
˓→SIMPLE)
# compatible with opencv3.x and openc4.x
if len(_tuple) == 3:
_, contours, hierarchy = _tuple
else:
contours, hierarchy = _tuple
color_area_num = len(contours) # Count the number of contours
if color_area_num > 0:
for i in contours: # Traverse all contours
x,y,w,h = cv2.boundingRect(i) # Decompose the contour into the
˓→coordinates of the upper left corner and the width and height of the recognition
˓→object
# Draw a rectangle on the image (picture, upper left corner coordinate,
˓→lower right corner coordinate, color, line width)
if w >= 8 and h >= 8: # Because the picture is reduced to a quarter of
˓→the original size, if you want to draw a rectangle on the original picture to
˓→circle the target, you have to multiply x, y, w, h by 4.
x = x
*
4
y = y
*
4
w = w
*
4
h = h
*
4
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) # Draw a rectangular
˓→frame
cv2.putText(img,color_type,(x,y), cv2.FONT_HERSHEY_SIMPLEX, 1,(0,0,
˓→255),2)# Add character description
return img,mask,morphologyEx_img
The img , mask , and morphologyEx_img are displayed in three windows to directly observe the processing
results of each step.
4.8. Color Detection 67