import cv2 import numpy as np def clearColor img axes cols cv2 split i

 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
import cv2
import numpy as np
def clearColor(img, axes):
cols = cv2.split(img)
sum = np.zeros(cols[0].shape, np.float)
for i in cols:
sum = np.add(sum, i)
return [cv2.divide(cols[i].astype(float), sum) for i in axes]
cap = cv2.VideoCapture(1)
h, w = cap.read()[1].shape[:2]
norm_rect = ((w / 3, h / 2), (2 * w / 3, h))
while (1):
_, frame = cap.read()
cv2.rectangle(frame, norm_rect[0], norm_rect[1], (0, 255, 0), 2)
cv2.imshow('frame', frame)
k = cv2.waitKey(10)
if k >= 0:
break
cv2.destroyWindow('frame')
ret,frame = cap.read()
# setup initial location of window
r, h, c, w = h / 2, h / 2, w / 3, w / 3
# r,h,c,w = 250,90,400,125 # simply hardcoded the values
track_window = (c,r,w,h)
# set up the ROI for tracking
roi = frame[r:r+h, c:c+w]
hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.)))
roi_hist = cv2.calcHist([hsv_roi],[0],mask,[180],[0,180])
cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)
# Setup the termination criteria, either 10 iteration or move by atleast 1 pt
term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )
c=0
while True:
_, frame = cap.read()
if frame is None:
continue
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
hue, sat, bri = cv2.split(hsv)
dst = cv2.calcBackProject([hsv],[0],roi_hist,[0,180],1)
ret, track_window = cv2.meanShift(dst, track_window, term_crit)
x,y,w,h = track_window
cx = x + w / 2
cy = y + h / 2
canny = cv2.Canny(hue, 50, 80, None, 3)
count, hie = cv2.findContours(canny, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
ccc = np.zeros(hue.shape[:2], np.uint8)
cv2.drawContours(ccc, count, -1, 255, 1)
ccc = cv2.dilate(ccc, np.ones((3, 3), np.uint8), iterations=5)
ccc = cv2.erode(ccc, np.ones((3, 3), np.uint8), iterations=1)
tmp1 = np.zeros(ccc.shape[:2], np.uint8)
tmp2 = np.zeros(ccc.shape[:2], np.uint8)
tmp = cv2.merge([ccc, tmp1, tmp2])
cv2.floodFill(tmp, None, (cx, cy), (0, 255))
tmp1 = cv2.split(tmp)[1]
tmp2 = np.copy(tmp1)
contours = cv2.findContours(tmp2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0]
th_area_min = 2000
th_area_max = 20000
tmp1 = cv2.cvtColor(tmp1, cv2.COLOR_GRAY2BGR)
for i in contours:
area = cv2.contourArea(i)
if area < th_area_max and area > th_area_min:
cv2.drawContours(tmp1, [i], 0, (0, 255, 0), 1)
cv2.imshow('green', tmp1)
#cv2.imshow('3', ccc)
k = cv2.waitKey(10)
if k == 13:
cv2.imwrite('./photos/' + str(c) + '.png', cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY))
c += 1
if k == 27:
break
cv2.destroyAllWindows()
cap.release()