-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathgreenball_tracker.py
executable file
·103 lines (70 loc) · 2.62 KB
/
greenball_tracker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env python
'''
Track a green ball using OpenCV.
Copyright (C) 2015 Conan Zhao and Simon D. Levy
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import cv2
import numpy as np
# For OpenCV2 image display
WINDOW_NAME = 'GreenBallTracker'
def track(image):
'''Accepts BGR image as Numpy array
Returns: (x,y) coordinates of centroid if found
(-1,-1) if no centroid was found
None if user hit ESC
'''
# Blur the image to reduce noise
blur = cv2.GaussianBlur(image, (5, 5), 0)
# Convert BGR to HSV
hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)
# Threshold the HSV image for only green colors
lower_green = np.array([40, 70, 70])
upper_green = np.array([80, 200, 200])
# Threshold the HSV image to get only green colors
mask = cv2.inRange(hsv, lower_green, upper_green)
# Blur the mask
bmask = cv2.GaussianBlur(mask, (5, 5), 0)
# Take the moments to get the centroid
moments = cv2.moments(bmask)
m00 = moments['m00']
centroid_x, centroid_y = None, None
if m00 != 0:
centroid_x = int(moments['m10']/m00)
centroid_y = int(moments['m01']/m00)
# Assume no centroid
ctr = (-1, -1)
# Use centroid if it exists
if centroid_x is not None and centroid_y is not None:
ctr = (centroid_x, centroid_y)
# Put black circle in at centroid in image
cv2.circle(image, ctr, 4, (0, 0, 0))
# Display full-color image
cv2.imshow(WINDOW_NAME, image)
# Force image display, setting centroid to None on ESC key input
if cv2.waitKey(1) & 0xFF == 27:
ctr = None
# Return coordinates of centroid
return ctr
# Test with input from camera
if __name__ == '__main__':
capture = cv2.VideoCapture(0)
while True:
okay, image = capture.read()
if okay:
if not track(image):
break
if cv2.waitKey(1) & 0xFF == 27:
break
else:
print('Capture failed')
break