-
Notifications
You must be signed in to change notification settings - Fork 2
/
ball_track.py
43 lines (34 loc) · 1.18 KB
/
ball_track.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
import cv2
import numpy as np
def getthresholdedimg(hsv):
yellow = cv2.inRange(hsv,np.array((20,100,100)),np.array((30,255,255)))
blue = cv2.inRange(hsv,np.array((100,100,100)),np.array((120,255,255)))
both = cv2.add(yellow,blue)
return both
c = cv2.VideoCapture(0)
width,height = c.get(3),c.get(4)
print "frame width and height : ", width, height
while(1):
_,f = c.read()
f = cv2.flip(f,1)
blur = cv2.medianBlur(f,5)
hsv = cv2.cvtColor(f,cv2.COLOR_BGR2HSV)
both = getthresholdedimg(hsv)
erode = cv2.erode(both,None,iterations = 3)
dilate = cv2.dilate(erode,None,iterations = 10)
contours = cv2.findContours(dilate,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
print cnt
x,y,w,h = cv2.boundingRect(cnt)
cx,cy = x+w/2, y+h/2
if 20 < hsv.item(cy,cx,0) < 30:
cv2.rectangle(f,(x,y),(x+w,y+h),[0,255,255],2)
print "yellow :", x,y,w,h
elif 100 < hsv.item(cy,cx,0) < 120:
cv2.rectangle(f,(x,y),(x+w,y+h),[255,0,0],2)
print "blue :", x,y,w,h
cv2.imshow('img',f)
if cv2.waitKey(25) == 27:
break
cv2.destroyAllWindows()
c.release()