a061ae0350e8e430a3c0b432d1f13b7262be3fd2
[opencv] / samples / python / facedetect.py
1 #!/usr/bin/python
2 """
3 This program is demonstration for face and object detection using haar-like features.
4 The program finds faces in a camera image or video stream and displays a red box around them.
5
6 Original C implementation by:  ?
7 Python implementation by: Roman Stanchak
8 """
9 import sys
10 from opencv.cv import *
11 from opencv.highgui import *
12
13
14 # Global Variables
15 cascade = None
16 storage = cvCreateMemStorage(0)
17 cascade_name = "../../data/haarcascades/haarcascade_frontalface_alt.xml"
18 input_name = "../c/lena.jpg"
19
20 # Parameters for haar detection
21 # From the API:
22 # The default parameters (scale_factor=1.1, min_neighbors=3, flags=0) are tuned 
23 # for accurate yet slow object detection. For a faster operation on real video 
24 # images the settings are: 
25 # scale_factor=1.2, min_neighbors=2, flags=CV_HAAR_DO_CANNY_PRUNING, 
26 # min_size=<minimum possible face size
27 min_size = cvSize(20,20)
28 image_scale = 1.3
29 haar_scale = 1.2
30 min_neighbors = 2
31 haar_flags = 0
32
33
34 def detect_and_draw( img ):
35     gray = cvCreateImage( cvSize(img.width,img.height), 8, 1 );
36     small_img = cvCreateImage( cvSize( cvRound (img.width/image_scale),
37                                                                cvRound (img.height/image_scale)), 8, 1 );
38     cvCvtColor( img, gray, CV_BGR2GRAY );
39     cvResize( gray, small_img, CV_INTER_LINEAR );
40
41     cvEqualizeHist( small_img, small_img );
42     
43     cvClearMemStorage( storage );
44
45     if( cascade ):
46         t = cvGetTickCount();
47         faces = cvHaarDetectObjects( small_img, cascade, storage,
48                                      haar_scale, min_neighbors, haar_flags, min_size );
49         t = cvGetTickCount() - t;
50         print "detection time = %gms" % (t/(cvGetTickFrequency()*1000.));
51         if faces:
52             for r in faces:
53                 pt1 = cvPoint( int(r.x*image_scale), int(r.y*image_scale))
54                 pt2 = cvPoint( int((r.x+r.width)*image_scale), int((r.y+r.height)*image_scale) )
55                 cvRectangle( img, pt1, pt2, CV_RGB(255,0,0), 3, 8, 0 );
56
57     cvShowImage( "result", img );
58
59
60 if __name__ == '__main__':
61
62     if len(sys.argv) > 1:
63
64         if sys.argv[1].startswith("--cascade="):
65             cascade_name = sys.argv[1][ len("--cascade="): ]
66             if len(sys.argv) > 2:
67                 input_name = sys.argv[2]
68
69         elif sys.argv[1] == "--help" or sys.argv[1] == "-h":
70             print "Usage: facedetect --cascade=\"<cascade_path>\" [filename|camera_index]\n" ;
71             sys.exit(-1)
72
73         else:
74             input_name = sys.argv[1]
75     
76     # the OpenCV API says this function is obsolete, but we can't
77     # cast the output of cvLoad to a HaarClassifierCascade, so use this anyways
78     # the size parameter is ignored
79     cascade = cvLoadHaarClassifierCascade( cascade_name, cvSize(1,1) );
80     
81     if not cascade:
82         print "ERROR: Could not load classifier cascade"
83         sys.exit(-1)
84     
85
86     if input_name.isdigit():
87         capture = cvCreateCameraCapture( int(input_name) )
88     else:
89         capture = cvCreateFileCapture( input_name ); 
90
91     cvNamedWindow( "result", 1 );
92
93     if( capture ):
94         frame_copy = None
95         while True: 
96             frame = cvQueryFrame( capture );
97             if( not frame ):
98                 break;
99             if( not frame_copy ):
100                 frame_copy = cvCreateImage( cvSize(frame.width,frame.height),
101                                             IPL_DEPTH_8U, frame.nChannels );
102             if( frame.origin == IPL_ORIGIN_TL ):
103                 cvCopy( frame, frame_copy );
104             else:
105                 cvFlip( frame, frame_copy, 0 );
106             
107             detect_and_draw( frame_copy );
108
109             if( cvWaitKey( 10 ) >= 0 ):
110                 break;
111
112     else:
113         image = cvLoadImage( input_name, 1 );
114
115         if( image ):
116         
117             detect_and_draw( image );
118             cvWaitKey(0);
119         
120     cvDestroyWindow("result");