Today marks the 100th blog post on PyImageSearch.
100 posts. It’s hard to believe it, but it’s true.
When I started PyImageSearch back in January of 2014, I had no idea what the blog would turn into. I didn’t know how it would evolve and mature. And I most certainly did not know how popular it would become. After 100 blog posts, I think the answer is obvious now, although I struggled to put it into words (ironic, since I’m a writer) until I saw this tweet from @si2w:
I couldn’t agree more. And I hope the rest of the PyImageSearch readers do as well.
It’s been an incredible ride and I really have you, the PyImageSearch readers to thank. Without you, this blog really wouldn’t have been possible.
That said, to make the 100th blog post special, I thought I would do something a fun — ball tracking with OpenCV:
The goal here is fair self-explanatory:
- Step #1: Detect the presence of a colored ball using computer vision techniques.
- Step #2: Track the ball as it moves around in the video frames, drawing its previous positions as it moves.
The end product should look similar to the GIF and video above.
After reading this blog post, you’ll have a good idea on how to track balls (and other objects) in video streams using Python and OpenCV.
Looking for the source code to this post?
Jump right to the downloads section.
Jump right to the downloads section.
Ball tracking with OpenCV
Let’s get this example started. Open up a new file, name it ball_tracking.py , and we’ll get coding:
Lines 2-6 handle importing our necessary packages. We’ll be using deque , a list-like data structure with super fast appends and pops to maintain a list of the past N (x, y)-locations of the ball in our video stream. Maintaining such a queue allows us to draw the “contrail” of the ball as its being tracked.
We’ll also be using imutils , my collection of OpenCV convenience functions to make a few basic tasks (like resizing) much easier. If you don’t already have imutils installed on your system, you can grab the source from GitHub or just use pip to install it:
From there, Lines 9-14 handle parsing our command line arguments. The first switch, --video is the (optional) path to our example video file. If this switch is supplied, then OpenCV will grab a pointer to the video file and read frames from it. Otherwise, if this switch is not supplied, then OpenCV will try to access our webcam.
If this your first time running this script, I suggest using the --video switch to start: this will demonstrate the functionality of the Python script to you, then you can modify the script, video file, and webcam access to your liking.
A second optional argument, --buffer is the maximum size of our deque , which maintains a list of the previous (x, y)-coordinates of the ball we are tracking. This deque allows us to draw the “contrail” of the ball, detailing its past locations. A smaller queue will lead to a shorter tail whereas a larger queue will create a longer tail (since more points are being tracked):
Figure 1: An example of a short contrail (buffer=32) on the left, and a longer contrail (buffer=128) on the right. Notice that as the size of the buffer increases, so does the length of the contrail.
Now that our command line arguments are parsed, let’s look at some more code:
Lines 19 and 20 define the lower and upper boundaries of the color green in the HSV color space (which I determined using the range-detector script in the imutils library). These color boundaries will allow us to detect the green ball in our video file. Line 21 then initializes our deque of pts using the supplied maximum buffer size (which defaults to 64 ).
From there, we need to grab access to our camera pointer. If a --video switch was not supplied, then we grab reference to our webcam (Lines 25 and 26). Otherwise, if a video file path was supplied, then we open it for reading and grab a reference pointer on Lines 29 and 30.
Line 33 starts a loop that will continue until (1) we press the q key, indicating that we want to terminate the script or (2) our video file reaches its end and runs out of frames.
Line 35 makes a call to the read method of our camera pointer which returns a 2-tuple. The first entry in the tuple, grabbed is a boolean indicating whether the frame was successfully read or not. The frame is the video frame itself.
In the case we are reading from a video file and the frame is not successfully read, then we know we are at the end of the video and can break from the while loop (Lines 39 and 40).
Lines 44-46 preprocess our frame a bit. First, we resize the frame to have a width of 600px. Downsizing the frame allows us to process the frame faster, leading to an increase in FPS (since we have less image data to process). We’ll then blur the frame to reduce high frequency noise and allow us to focus on the structural objects inside the frame , such as the ball. Finally, we’ll convert the frame to the HSV color space.
Lines 51 handles the actual localization of the green ball in the frame by making a call tocv2.inRange . We first supply the lower HSV color boundaries for the color green, followed by the upper HSV boundaries. The output of cv2.inRange is a binary mask , like this one:
As we can see, we have successfully detected the green ball in the image. A series of erosions and dilations (Lines 52 and 53) remove any small blobs that my be left on the mask.
Alright, time to perform compute the contour (i.e. outline) of the green ball and draw it on ourframe :
We start by computing the contours of the object(s) in the image on Line 57. We specify an array slice of -2 to make the cv2.findContours function compatible with both OpenCV 2.4 and OpenCV 3. You can read more about why this change to cv2.findContours is necessary in this blog post. We’ll also initialize the center (x, y)-coordinates of the ball toNone on Line 59.
Line 62 makes a check to ensure at least one contour was found in the mask . Provided that at least one contour was found, we find the largest contour in the cnts list on Line 66, compute the minimum enclosing circle of the blob, and then compute the center (x, y)-coordinates (i.e. the “centroids) on Lines 68 and 69.
Line 72 makes a quick check to ensure that the radius of the minimum enclosing circle is sufficiently large. Provided that the radius passes the test, we then draw two circles: one surrounding the ball itself and another to indicate the centroid of the ball.
Finally, Line 80 appends the centroid to the pts list.
The last step is to draw the contrail of the ball, or simply the past N (x, y)-coordinates the ball has been detected at. This is also a straightforward process:
We start looping over each of the pts on Line 84. If either the current point or the previous point is None (indicating that the ball was not successfully detected in that given frame), then we ignore the current index continue looping over the pts (Lines 86 and 87).
Provided that both points are valid, we compute the thickness of the contrail and then draw it on the frame (Lines 91 and 92).
The remainder of our ball_tracking.py script simply performs some basic housekeeping by displaying the frame to our screen, detecting any key presses, and then releasing thecamera pointer.
Ball tracking in action
Now that our script has been coded it up, let’s give it a try. Open up a terminal and execute the following command:
This command will kick off our script using the supplied ball_tracking_example.mp4 demo video. Below you can find a few animated GIFs of the successful ball detection and tracking using OpenCV:
For the full demo, please see the video below:
Finally, if you want to execute the script using your webcam rather than the supplied video file, simply omit the --video switch:
However, to see any results, you will need a green object with the same HSV color range was the one I used in this demo.
Summary
In this blog post we learned how to perform ball tracking with OpenCV. The Python script we developed was able to (1) detect the presence of the colored ball, followed by (2) track and draw the position of the ball as it moved around the screen.
As the results showed, our system was quite robust and able to track the ball even if it was partially occluded from view by my hand.
Our script was also able to operate at an extremely high frame rate (> 32 FPS), indicating that color based tracking methods are very much suitable for real-time detection and tracking.
If you enjoyed this blog post, please consider subscribing to the PyImageSearch Newsletter by entering your email address in the form below — this blog (and the 99 posts preceding it) wouldn’t be possible without readers like yourself.
Komentar
Posting Komentar