Tag Archives: OpenCV

Use OpenCV to detect faces in a picture

I used to learn OpenCV and wrote a face detect application with python according to the sample in OpenCV’s package. But the API of OpenCV 2.1 is quite different with that in 2.0 version. I modified my code and then it worked in OpenCV 2.1 now. Here is the code.

import cv

image_path = 'IMG_1782.JPG' #'Me.jpeg'
cascade_name = 'haarcascade_frontalface_alt.xml'

if __name__ == '__main__':
	image = cv.LoadImageM(image_path, 1)
	image_size = (image.width, image.height)
	grayscale = cv.CreateImage(image_size, 8, 1)
	small_img = cv.CreateImage((cv.Round(image.width/1.3), cv.Round (image.height/1.3)), 8, 1 )

	cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY)
	cv.Resize( grayscale, small_img, cv.CV_INTER_LINEAR )

	cv.EqualizeHist( small_img, small_img )
	storage = cv.CreateMemStorage(0)

	cascade = cv.Load(cascade_name)
	faces = cv.HaarDetectObjects(small_img, cascade, storage, 1.2, 2, 0, (20, 20))
	if faces:
		for (x,y,w,h),n in faces:
			# the input to cvHaarDetectObjects was resized, so scale the
			# bounding box of each face and convert it to two CvPoints
			pt1 = ( int(x*1.3), int(y*1.3))
			pt2 = ( int((x+w)*1.3), int((y+h)*1.3) )
			cv.Rectangle( image, pt1, pt2, cv.CV_RGB(255,0,0), 3, 8, 0 )
	cv.ShowImage( "result", image )
	cv.WaitKey(0)