import cv2 import numpy as np import test cap cv2 VideoCapture avg tes

 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
import cv2
import numpy as np
import test
cap = cv2.VideoCapture(0)
avg = test.norm(cap)
th = 70
lower_th = tuple([int(i - th) for i in avg])
upper_th = tuple([int(i + th) for i in avg])
print lower_th, avg, upper_th
while( cap ) :
ret, img = cap.read()
if img is None:
continue
mask = np.copy(img)
mask = cv2.inRange(img, lower_th, upper_th, mask)
mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
res = np.copy(img)
cv2.bitwise_and(img, mask, res)
img = np.copy(res)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
# # blur = test.doIt(blur, avg, 50)
ret,thresh1 = cv2.threshold(blur,th,255,cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
drawing = np.zeros(img.shape,np.uint8)
max_area=0
ci = 0
for i in range(len(contours)):
cnt=contours[i]
area = cv2.contourArea(cnt)
if(area>max_area):
max_area=area
ci=i
if (len(contours) == 0):
continue
cnt=contours[ci]
hull = cv2.convexHull(cnt)
moments = cv2.moments(cnt)
if moments['m00']!=0:
cx = int(moments['m10']/moments['m00']) # cx = M10/M00
cy = int(moments['m01']/moments['m00']) # cy = M01/M00
centr=(cx,cy)
cv2.circle(img,centr,5,[0,0,255],2)
cv2.drawContours(drawing,[cnt],0,(0,255,0),2)
# cv2.drawContours(drawing,[hull],0,(0,0,255),2)
cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
hull = cv2.convexHull(cnt,returnPoints = False)
if(1):
defects = cv2.convexityDefects(cnt,hull)
mind=0
maxd=0
if defects is None:
continue
for i in range(defects.shape[0]):
s,e,f,d = defects[i,0]
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
dist = cv2.pointPolygonTest(cnt,centr,True)
cv2.line(img,start,end,[0,255,0],2)
cv2.circle(img,far,5,[0,0,255],-1)
i=0
cv2.imshow('output',drawing)
cv2.imshow('input',thresh1)
# cv2.imshow('res',res)
# cv2.imshow('mask',mask)
# cv2.imshow('src',img)
k = cv2.waitKey(10)
if k == 27:
break