EasyManua.ls Logo

SunFounder picar-x - Page 70

Default Icon
153 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
SunFounder picar-x
(continued from previous page)
img = frame.array
img,img_2,img_3 = color_detect(img,'red') # Color detection function
cv2.imshow("video", img) # OpenCV image show
cv2.imshow("mask", img_2) # OpenCV image show
cv2.imshow("morphologyEx_img", img_3) # OpenCV image show
rawCapture.truncate(0) # Release cache
k = cv2.waitKey(1) & 0xFF
# 27 is the ESC key, which means that if you press the ESC key to exit
if k == 27:
break
print('quit ...')
cv2.destroyAllWindows()
camera.close()
How it works?
First, the range of H in the HSV color space is defined as a dictionary, which is convenient for the following color
judgment algorithm:
color_dict = {'red':[0,4],'orange':[5,18],'yellow':[22,37],'green':[42,85],'blue':[92,
˓110],'purple':[115,165],'red_2':[165,180]}
Then, a convolution kernel of size 5x5 is defined, which will be used for morphological operations, like filtering.
kernel_5 = np.ones((5,5),np.uint8)
Next, the color_detect() function will processes pictures in four steps:
1. Extract the data of the target color as a new binary image (array).
2. Performs advanced morphological transformations.
3. Finds contours in a binary image.
4. Draws a frame for the recognized object on the image.
def color_detect(img,color_name):
# The blue range will be different under different lighting conditions and can be
˓adjusted flexibly. H: chroma, S: saturation v: lightness
resize_img = cv2.resize(img, (160,120), interpolation=cv2.INTER_LINEAR) # In
˓order to reduce the amount of calculation, the size of the picture is reduced to
˓(160,120)
hsv = cv2.cvtColor(resize_img, cv2.COLOR_BGR2HSV) # Convert from BGR
˓to HSV
color_type = color_name
mask = cv2.inRange(hsv,np.array([min(color_dict[color_type]), 60, 60]), np.
˓array([max(color_dict[color_type]), 255, 255]) ) # inRange()Make the ones
˓between lower/upper white, and the rest black
if color_type == 'red':
mask_2 = cv2.inRange(hsv, (color_dict['red_2'][0],0,0), (color_dict['red_2
˓'][1],255,255))
mask = cv2.bitwise_or(mask, mask_2)
morphologyEx_img = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel_5,iterations=1)
˓ # Perform an open operation on the image
(continues on next page)
66 Chapter 4. Play with Python

Related product manuals