Face recognition is always seen in sci-fi movies. Now we can also program it. Ha ha ~
OpenCV is an Intel < open source computer vision library. It consists of a series of C functions and a few C++ classes. It realizes many general algorithms in image processing and computer vision.
OpenCV has a cross-platform, high-level API that includes more than 300 C functions. It does not depend on other external libraries -- although some external libraries can also be used. It also provides the interface of Python, Ruby, MATLAB and other languages, and realizes image processing and computer vision.
Many general algorithms of surface.
So in general, OpenCV's face detection function is very good.
The results are as follows:
Next, we use python + OpenCV to realize face recognition.
Development and operation environment:
Centos5.5
OpenCV
python2.7
PIL
The following code:
import sys, os #Introducing corresponding components in opencv Library from opencv.cv import * from opencv.highgui import * #Introducing PIL Library from PIL import Image, ImageDraw from math import sqrt ''' //Want to learn Python? Python Learning Exchange Group: 984632579 to meet your needs, information has been uploaded group files, you can download! ''' def detectObjects(image): #Firstly, the image is transformed into gray mode to find the face position. grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1) cvCvtColor(image, grayscale, CV_BGR2GRAY) storage = cvCreateMemStorage(0) cvClearMemStorage(storage) cvEqualizeHist(grayscale, grayscale) cascade = cvLoadHaarClassifierCascade( \'/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml\', cvSize(1,1)) faces = cvHaarDetectObjects(grayscale, cascade, storage, 1.1, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(20,20)) result = [] for f in faces: result.append((f.x, f.y, f.x+f.width, f.y+f.height)) return result def grayscale(r, g, b): return int(r * .3 + g * .59 + b * .11) def process(infile, outfile): image = cvLoadImage(infile); if image: faces = detectObjects(image) im = Image.open(infile) if faces: draw = ImageDraw.Draw(im) for f in faces: draw.rectangle(f, outline=(255, 0, 255)) im.save(outfile, "JPEG", quality=100) else: print "Error: cannot detect faces on %s" % infile if __name__ == "__main__": process(\'input.jpg\', \'output.jpg\')
This is the end of the code, the above examples do not understand, it doesn't matter, because we use a lot of functions and methods in the library, if you do not understand, we can go online to look up or use the manual, as long as you understand this code, ok, the important thing is to grasp the realization idea of face recognition.