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.
6 Original C implementation by: ?
7 Python implementation by: Roman Stanchak
10 from opencv.cv import *
11 from opencv.highgui import *
16 storage = cvCreateMemStorage(0)
17 cascade_name = "../../data/haarcascades/haarcascade_frontalface_alt.xml"
18 input_name = "../c/lena.jpg"
20 # Parameters for haar detection
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)
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 );
41 cvEqualizeHist( small_img, small_img );
43 cvClearMemStorage( storage );
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.));
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 );
57 cvShowImage( "result", img );
60 if __name__ == '__main__':
64 if sys.argv[1].startswith("--cascade="):
65 cascade_name = sys.argv[1][ len("--cascade="): ]
67 input_name = sys.argv[2]
69 elif sys.argv[1] == "--help" or sys.argv[1] == "-h":
70 print "Usage: facedetect --cascade=\"<cascade_path>\" [filename|camera_index]\n" ;
74 input_name = sys.argv[1]
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) );
82 print "ERROR: Could not load classifier cascade"
86 if input_name.isdigit():
87 capture = cvCreateCameraCapture( int(input_name) )
89 capture = cvCreateFileCapture( input_name );
91 cvNamedWindow( "result", 1 );
96 frame = cvQueryFrame( capture );
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 );
105 cvFlip( frame, frame_copy, 0 );
107 detect_and_draw( frame_copy );
109 if( cvWaitKey( 10 ) >= 0 ):
113 image = cvLoadImage( input_name, 1 );
117 detect_and_draw( image );
120 cvDestroyWindow("result");