The
OpenCV's official Python tutorial is already in the converting Color space section (https://docs.opencv.org/master/df/d9d/tutorial_py_ colorspaces.html) gives the basic method of tracking a particular color object: converting the color space to HSV, setting the color threshold of the tracked object, and doing the binary processing. We have improved this by filtering out some of the noise and using the minimum circumscribed circle to circle the object to be traced, the code is as follows, and the comments are not detailed in detail:
# Importing Required modules import CV2 as CV import numpy as NP import imutils # Open Camera cap = CV. Videocapture (0) while True: # reads each frame _, frame = Cap.read () # Resets the picture size to increase the calculation speed frame = Imutils.resize (frame, W idth=600) # for Gaussian blur blurred = cv. Gaussianblur (frame, (11, 11), 0) # Converts the color space to HSV HSV = Cv.cvtcolor (blurred, CV. COLOR_BGR2HSV) # Defines the HSV threshold for red no graph lower_red = Np.array ([[255], []) upper_red = Np.array ([220, 255,]) #
Binary image Processing mask = Cv.inrange (HSV, lower_red, upper_red) # corrosion Operation mask = Cv.erode (Mask, None, iterations=2) # expansion operation, first corrosion after expansion to filter out the noise mask = cv.dilate (Mask, None, iterations=2) cv.imshow (' Mask ', mask) # Look for the outline in the figure CNTs = CV . Findcontours (Mask.copy (), CV. Retr_external, CV. Chain_approx_simple) [-2] # If there is at least one profile then do the following if Len (CNTs) > 0: # Find the area with the largest contour c = max (CNTs, Key=c V.contourarea) # uses the smallest circumscribed circle to circle the largest contour ((x, y), radius) = Cv.minenclosingcircle (c) # Calculates the moment of the contour M =
Cv.moments (c) # Calculate the center of gravity Center = (int (m["M10"]/m["m00"]), int (m["m01"]/m["m00"]) # only deal with contours with large enough size if Radi
US > 5: # Draw minimum circumscribed circle cv.circle (frame, (int (x), int (y)), int (RADIUS), (0, 255, 255), 2) # Draw center of Gravity cv.circle (frame, center, 5, (0, 0, 255),-1) cv.imshow (' frame ', frame) k = Cv.waitkey (5) & ; 0xFF if k = = 27:break cap.release () cv.destroyallwindows ()