计算机视觉之人脸识别看起来很高大上,但是用OpenCV解决很方便,OpenCV真的太强大了。OpenCV中人脸检测使用的是 detectMultiScale函数,它可以检测出图片中所有的人脸,并将人脸用vector保存各个人脸的坐标、大小(用矩形表示),函数由分类器对象调用:
cv::CascadeClassifier::detectMultiScale( const cv::Mat& image, // Input (grayscale) image vector<cv::Rect>& objects, // Output boxes (boxen?) double scaleFactor = 1.1, // Factor between scales int minNeighbors = 3, // Required neighbors to count int flags = 0, // Flags (old style cascades) cv::Size minSize = cv::Size(), // Smallest we will consider cv::Size maxSize = cv::Size() // Largest we will consider );
直接上代码示例,Python版的。
#!/usr/bin/env python import cv2 # 读取图片 image = cv2.imread("demo.jpg") gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 加载分类器 classifier = cv2.CascadeClassifier() classifier.load("haarcascade_frontalface_default.xml") faces = classifier.detectMultiScale(gray_img, 1.1, 3) # 绘制识别出来的人脸 for (x, y, w, h) in faces: src = cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 255), 2) cv2.imshow('Result Image', image) cv2.waitKey(0) cv2.destroyAllWindows()