-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathball_detect_live.py
90 lines (72 loc) · 2.98 KB
/
ball_detect_live.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
#!/usr/bin/env python
import numpy as np
import cv2
import rospy
def read_rgb_image(image_name, show):
rgb_image = cv2.imread(image_name)
if show:
cv2.imshow("RGB Image",rgb_image)
return rgb_image
def filter_color(rgb_image, lower_bound_color, upper_bound_color):
#convert the image into the HSV color space
hsv_image = cv2.cvtColor(rgb_image, cv2.COLOR_BGR2HSV)
cv2.imshow("hsv image",hsv_image)
#find the upper and lower bounds of the yellow color (tennis ball)
yellowLower =(30, 150, 100)
yellowUpper = (50, 255, 255)
#define a mask using the lower and upper bounds of the yellow color
mask = cv2.inRange(hsv_image, lower_bound_color, upper_bound_color)
return mask
def getContours(binary_image):
#_, contours, hierarchy = cv2.findContours(binary_image,
# cv2.RETR_TREE,
# cv2.CHAIN_APPROX_SIMPLE)
contours, hierarchy = cv2.findContours(binary_image.copy(),
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
return contours
def draw_ball_contour(binary_image, rgb_image, contours):
black_image = np.zeros([binary_image.shape[0], binary_image.shape[1],3],'uint8')
for c in contours:
area = cv2.contourArea(c)
perimeter= cv2.arcLength(c, True)
((x, y), radius) = cv2.minEnclosingCircle(c)
if (area>100):
cv2.drawContours(rgb_image, [c], -1, (150,250,150), 1)
cv2.drawContours(black_image, [c], -1, (150,250,150), 1)
cx, cy = get_contour_center(c)
cv2.circle(rgb_image, (cx,cy),(int)(radius),(0,0,255),1)
cv2.circle(black_image, (cx,cy),(int)(radius),(0,0,255),1)
cv2.circle(black_image, (cx,cy),5,(150,150,255),-1)
print ("Area: {}, Perimeter: {}".format(area, perimeter))
print ("number of contours: {}".format(len(contours)))
cv2.imshow("RGB Image Contours",rgb_image)
cv2.imshow("Black Image Contours",black_image)
def get_contour_center(contour):
M = cv2.moments(contour)
cx=-1
cy=-1
if (M['m00']!=0):
cx= int(M['m10']/M['m00'])
cy= int(M['m01']/M['m00'])
return cx, cy
def main(image_name):
yellowLower =(30, 150, 100)
yellowUpper = (50, 255, 255)
binary_image_mask = filter_color(image_name, yellowLower, yellowUpper)
contours = getContours(binary_image_mask)
draw_ball_contour(binary_image_mask, image_name,contours)
cv2.waitKey(1)
if __name__ == '__main__':
vid = '/home/abdu/catkin_ws/src/ros_essentials_cpp/src/topic03_perception/video/tennis-ball-video.mp4'
cap = cv2.VideoCapture(vid)
while(True):
_,image_name = cap.read()
try :
main(image_name)
except rospy.ROSInterruptException as e:
break
cap.release()
cv2.destroyAllWindows()
# cv2.waitKey(0)
# cv2.destroyAllWindows()