In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how to track objects with specified colors through OpenCV. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
To track objects of a particular color, I used the leaves of green apple in my experiment.
Create a new script ball_tracking.py and add the code:
Import argparsefrom collections import dequeimport cv2import numpy as np
Import the necessary packages and define some functions
Def grab_contours (cnts): # if the length of the profile tuple returned by cv2.findContours is "2", then we are using OpenCV v2.4, v4-beta or v4-official if len (cnts) = = 2: cnts = cnts [0] # if the length of the profile tuple is "3" So we use OpenCV v3, v4-pre or v4-alpha elif len (cnts) = = 3: cnts = cnts [1] else: raise Exception ("Contours tuple must have length 2 or 3,"otherwise OpenCV changed their cv2.findContours return"signature yet again." Refer to OpenCV's documentation "" in that case ") return cntsdef resize (image, width=None, height=None, inter=cv2.INTER_AREA): dim = None (h W) = image.shape [: 2] # return if width is None and height is None directly if the height and width are None: return image # check whether the width is None if width is None: # calculate the height ratio and calculate the width r = height / float (h) dim = (int (w * r)) Height) # height is None else: # calculate width ratio And calculate the height r = width / float (w) dim = (width, int (h * r)) resized = cv2.resize (image, dim, interpolation=inter) # return the resized image return resized
Grab_contours is compatible with different versions of opencv.
Resize and other proportions change the size of the picture.
Command line parameter ap = argparse.ArgumentParser () ap.add_argument ("- v", "- video", help= "path to video") ap.add_argument ("- b", "- buffer", type=int, default=64, help= "max buffer size") args = vars (ap.parse_args ()) # HSV gamut space range of green leaves greenLower = (29,86,6) greenUpper = (64,255) Pts = deque (maxlen=args ["buffer"]) vs = cv2.VideoCapture (0) fps = 30 # FPS to save the video Size= (600450) fourcc=cv2.VideoWriter_fourcc (* 'XVID') videowrite=cv2.VideoWriter (' output.avi',fourcc,fps,size) can be adjusted appropriately
Define parameters
-video: path to the video file or id of the camera
-buffer is the maximum size of deque, which maintains a list of previous (x, y) coordinates of the ball we are tracking. This double-ended queue allows us to draw the "trajectory" of the ball, detailing its past position. Smaller queues will result in shorter tails, while larger queues will result in longer tails
Define the upper and lower bounds of hsv space
Activate camera 0
Finally, the definition of VideoWriter object is saved to realize the function of writing video.
While True: ret_val, frame = vs.read () if ret_val is False: break frame = resize (frame, width=600) # remove some high-frequency noise by Gaussian filtering Make the important data more prominent blurred = cv2.GaussianBlur (frame, (11,11), 0) # convert the picture to HSV hsv = cv2.cvtColor (blurred, cv2.COLOR_BGR2HSV) # inRange is binarized according to the threshold: the pixels within the threshold are set to white Outside the threshold setting is black (0) mask = cv2.inRange (hsv, greenLower, greenUpper) # the role of corrosion (erode) and expansion (dilate): # 1. Eliminate noise; # 2. Isolate independent image elements and join adjacent elements; # 3. Look for obvious maximum or minimum areas in the image mask = cv2.erode (mask, None, iterations=2) mask = cv2.dilate (mask, None, iterations=2)
Start a loop that lasts until (1) we press the Q key to indicate that we want to terminate the script or (2) our video file reaches the finish line and runs out of frames.
Read a frame and return two parameters. Whether the first parameter is successful or not, the second parameter is an image.
Break if it fails.
Some preprocessing of the image is carried out. First, we resize the frame to a width of 600 pixels. Shrinking frames allows us to process frames faster, thus improving FPS (because we have less image data to process). We then blur the frame to reduce high-frequency noise and enable us to focus on structural objects within the frame, such as balls. Finally, we convert the frame to the HSV color space.
The actual positioning of the green ball in the frame is handled by calling cv2.inRange. First provide the lower HSV color boundary for green, and then the upper HSV boundary. The output of cv2.inRange is a binary mask
# find the outline. The format of cv2.findContours return is different for different versions of opencv. So call imutils.grab_contours and do some compatibility processing cnts = cv2.findContours (mask.copy (), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = grab_contours (cnts) center = None # only proceed if at least one contour was found if len (cnts) > 0: # find the largest contour in the mask, then use it to compute the minimum enclosing circle # and centroid c = max (cnts) Key=cv2.contourArea) ((x, y), radius) = cv2.minEnclosingCircle (c) M = cv2.moments (c) # for 01 binary image M00 is the area of the contour. The following formula is used to calculate the center distance center = (int (M ["M10"] / M ["M00"]), int (M ["M01"] / M ["M00"]) # only proceed if the radius meets a minimum size if radius > 10: # draw the circle and centroid on the frame, then update the list of tracked points cv2.circle (frame, (int (x)) Int (y)), int (radius), (0255,255), 2) cv2.circle (frame, center, 5, (0,0,255),-1) pts.appendleft (center) for i in range (1, len (pts)): # if either of the tracked points are None Ignore them if pts [I-1] is None or pts [I] is None: continue # compute the thickness of the line and draw the connecting line thickness = int (np.sqrt (args ["buffer"] / float (I + 1)) * 2.5) cv2.line (frame, pts [I-1], pts [I], (0,0,255), thickness) cv2.imshow ("Frame") Frame) videowrite.write (frame) key = cv2.waitKey (1) & 0xFF if key = = ord ("Q"): breakvideowrite.release () vs.release () cv2.destroyAllWindows ()
Calculates the outline of the object in the image. In the next line, the center (x, y) coordinates of the ball are initialized to None.
Check to make sure at least one outline is found in the mask. Suppose you find at least one outline, find the largest outline in the cnts list, calculate the minimum bounding circle of blob, and then calculate the center (x, y) coordinates (that is, "centroid").
Check quickly to make sure that the radius of the minimum bounding circle is large enough. If the radius passes the test, we then draw two circles: one around the ball itself, and the other represents the center of mass of the ball.
Then, append the centroid to the pts list.
Loop through each pts. If the current or previous point is None (indicating that the ball was not successfully detected in the given frame), then we continue to cycle through the pts, ignoring the current index.
If both points are valid, we calculate the thickness of the track and draw it on the frame.
Thank you for reading! This is the end of this article on "how to track objects with specified colors through OpenCV". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.