1+ #!/usr/bin/env python
2+
3+ import cv
4+
5+ class Target :
6+
7+ def __init__ (self ):
8+ self .capture = cv .CaptureFromCAM (0 )
9+ cv .NamedWindow ("Target" , 1 )
10+
11+ def run (self ):
12+ # Capture first frame to get size
13+ frame = cv .QueryFrame (self .capture )
14+ frame_size = cv .GetSize (frame )
15+ color_image = cv .CreateImage (cv .GetSize (frame ), 8 , 3 )
16+ grey_image = cv .CreateImage (cv .GetSize (frame ), cv .IPL_DEPTH_8U , 1 )
17+ moving_average = cv .CreateImage (cv .GetSize (frame ), cv .IPL_DEPTH_32F , 3 )
18+
19+ first = True
20+
21+ while True :
22+ closest_to_left = cv .GetSize (frame )[0 ]
23+ closest_to_right = cv .GetSize (frame )[1 ]
24+
25+ color_image = cv .QueryFrame (self .capture )
26+
27+ # Smooth to get rid of false positives
28+ cv .Smooth (color_image , color_image , cv .CV_GAUSSIAN , 3 , 0 )
29+
30+ if first :
31+ difference = cv .CloneImage (color_image )
32+ temp = cv .CloneImage (color_image )
33+ cv .ConvertScale (color_image , moving_average , 1.0 , 0.0 )
34+ first = False
35+ else :
36+ cv .RunningAvg (color_image , moving_average , 0.020 , None )
37+
38+ # Convert the scale of the moving average.
39+ cv .ConvertScale (moving_average , temp , 1.0 , 0.0 )
40+
41+ # Minus the current frame from the moving average.
42+ cv .AbsDiff (color_image , temp , difference )
43+
44+ # Convert the image to grayscale.
45+ cv .CvtColor (difference , grey_image , cv .CV_RGB2GRAY )
46+
47+ # Convert the image to black and white.
48+ cv .Threshold (grey_image , grey_image , 70 , 255 , cv .CV_THRESH_BINARY )
49+
50+ # Dilate and erode to get people blobs
51+ cv .Dilate (grey_image , grey_image , None , 18 )
52+ cv .Erode (grey_image , grey_image , None , 10 )
53+
54+ storage = cv .CreateMemStorage (0 )
55+ contour = cv .FindContours (grey_image , storage , cv .CV_RETR_CCOMP , cv .CV_CHAIN_APPROX_SIMPLE )
56+ points = []
57+
58+ while contour :
59+ bound_rect = cv .BoundingRect (list (contour ))
60+ contour = contour .h_next ()
61+
62+ pt1 = (bound_rect [0 ], bound_rect [1 ])
63+ pt2 = (bound_rect [0 ] + bound_rect [2 ], bound_rect [1 ] + bound_rect [3 ])
64+ points .append (pt1 )
65+ points .append (pt2 )
66+ cv .Rectangle (color_image , pt1 , pt2 , cv .CV_RGB (255 ,0 ,0 ), 1 )
67+
68+ if len (points ):
69+ center_point = reduce (lambda a , b : ((a [0 ] + b [0 ]) / 2 , (a [1 ] + b [1 ]) / 2 ), points )
70+ cv .Circle (color_image , center_point , 40 , cv .CV_RGB (255 , 255 , 255 ), 1 )
71+ cv .Circle (color_image , center_point , 30 , cv .CV_RGB (255 , 100 , 0 ), 1 )
72+ cv .Circle (color_image , center_point , 20 , cv .CV_RGB (255 , 255 , 255 ), 1 )
73+ cv .Circle (color_image , center_point , 10 , cv .CV_RGB (255 , 100 , 0 ), 1 )
74+
75+ cv .ShowImage ("Target" , color_image )
76+
77+ # Listen for ESC key
78+ c = cv .WaitKey (7 ) % 0x100
79+ if c == 27 :
80+ break
81+
82+ if __name__ == "__main__" :
83+ t = Target ()
84+ t .run ()
0 commit comments