In this article, we share the example of python using opencv to achieve the specific code for color detection, for your reference, the specific content is as follows
Need to implement the function of reversing auxiliary mark detection, reversing auxiliary mark color has been determined, so do not need to use the deep learning method, that cost is too high, directly can use the color detection method.
1. First need to determine the HSV value of the target to be detected
import cv2 img = ('') gray = (img, cv2.COLOR_BGR2GRAY) hsv = (img, cv2.COLOR_BGR2HSV) def mouse_click(event, x, y, flags, para): if event == cv2.EVENT_LBUTTONDOWN: # Left mouse click print('PIX:', x, y) print("BGR:", img[y, x]) print("GRAY:", gray[y, x]) print("HSV:", hsv[y, x]) if __name__ == '__main__': ("img") ("img", mouse_click) while True: ('img', img) if () == ord('q'): break ()
2. Then use color detection to detect the specified target
import numpy as np import cv2 font = cv2.FONT_HERSHEY_SIMPLEX lower_red = ([0, 127, 128]) # Lower red threshold higher_red = ([10, 255, 255]) # Upper red threshold lower_yellow = ([15, 230, 230]) # Lower yellow threshold higher_yellow = ([35, 255, 255]) # Upper yellow threshold lower_blue = ([85,240,140]) higher_blue = ([100,255,165]) frame=("") img_hsv = (frame, cv2.COLOR_BGR2HSV) mask_red = (img_hsv, lower_red, higher_red) # Can be thought of as filtering out the red part to get a red mask # mask_yellow = (img_hsv, lower_yellow, higher_yellow) # Getting the green part of the mask mask_yellow = (mask_yellow, 7) # Median filtering mask_red = (mask_red, 7) # Median filtering mask_blue = (img_hsv, lower_blue, higher_blue) # Getting the green part of the mask mask_blue = (mask_blue, 7) # Median filtering #mask = cv2.bitwise_or(mask_green, mask_red) # three-part mask for bitwise-or operation print(mask_red) cnts1, hierarchy1 = (mask_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Contour Detection #Red cnts2, hierarchy2 = (mask_blue, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Contour Detection #Red cnts3, hierarchy3 = (mask_yellow, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) for cnt in cnts1: (x, y, w, h) = (cnt) # This function returns the four points of the matrix (frame, (x, y), (x + w, y + h), (0, 0, 255), 2) # Frame the detected color (frame, 'red', (x, y - 5), font, 0.7, (0, 0, 255), 2) for cnt in cnts2: (x, y, w, h) = (cnt) # This function returns the four points of the matrix (frame, (x, y), (x + w, y + h), (0, 0, 255), 2) # Frame the detected color (frame, 'blue', (x, y - 5), font, 0.7, (0, 0, 255), 2) for cnt in cnts3: (x, y, w, h) = (cnt) # This function returns the four points of the matrix (frame, (x, y), (x + w, y + h), (0, 255, 0), 2) # Frame the detected color (frame, 'yellow', (x, y - 5), font, 0.7, (0, 255, 0), 2) ('frame', frame) (0) ()
3. Effectiveness
This is the whole content of this article, I hope it will help you to learn more.