`opencv 可以实现的功能有很多,这次就试试人脸识别
省心的opencv在example中已经提供了 分类器的级联分类器的文件,省去重复造轮子,haarcascade_eye_tree_eyeglasses.xml,haarcascade_frontalface_alt.xml
程序加载分类器,和 梅西的照片
- int main(){
- Mat image;
- CascadeClassifier cascade, nestedCascade;
- if(!nestedCascade.load("./haarcascade_eye_tree_eyeglasses.xml")){
- cerr << "WARNING: Could not load classifier cascade for nested objects" << endl;
- }
- if(!cascade.load("./haarcascade_frontalface_alt.xml")){
- cerr << "ERROR: Could not load classifier cascade" << endl;
- return -1;
- }
- image = imread("messi.jpg");
- detectAndDraw( image, cascade, nestedCascade, 1);
- waitKey(0);
- return 0;
- }
复制代码
- void detectAndDraw( Mat& img, CascadeClassifier& cascade,
- CascadeClassifier& nestedCascade,
- double scale)
- {
- double t = 0;
- vector faces, faces2;
- const static Scalar colors[] =
- {
- Scalar(255,0,0),
- Scalar(255,128,0),
- Scalar(255,255,0),
- Scalar(0,255,0),
- Scalar(0,128,255),
- Scalar(0,255,255),
- Scalar(0,0,255),
- Scalar(255,0,255)
- };
- Mat gray, smallImg;
- cvtColor( img, gray, COLOR_BGR2GRAY );
- double fx = 1 / scale;
- resize( gray, smallImg, Size(), fx, fx, INTER_LINEAR_EXACT );
- equalizeHist( smallImg, smallImg );
- t = (double)getTickCount();
- cascade.detectMultiScale( smallImg, faces,
- 1.1, 2, 0
- //|CASCADE_FIND_BIGGEST_OBJECT
- //|CASCADE_DO_ROUGH_SEARCH
- |CASCADE_SCALE_IMAGE,
- Size(30, 30) );
- t = (double)getTickCount() - t;
- printf( "detection time = %g ms
- ", t*1000/getTickFrequency());
- for ( size_t i = 0; i < faces.size(); i++ )
- {
- Rect r = faces[i];
- Mat smallImgROI;
- vector nestedObjects;
- Point center;
- Scalar color = colors[i%8];
- int radius;
- double aspect_ratio = (double)r.width/r.height;
- if( 0.75 < aspect_ratio && aspect_ratio < 1.3 )
- {
- center.x = cvRound((r.x + r.width*0.5)*scale);
- center.y = cvRound((r.y + r.height*0.5)*scale);
- radius = cvRound((r.width + r.height)*0.25*scale);
- circle( img, center, radius, color, 3, 8, 0 );
- }
- else
- rectangle( img, Point(cvRound(r.x*scale), cvRound(r.y*scale)),
- Point(cvRound((r.x + r.width-1)*scale), cvRound((r.y + r.height-1)*scale)),
- color, 3, 8, 0);
- if( nestedCascade.empty() )
- continue;
- smallImgROI = smallImg( r );
- nestedCascade.detectMultiScale( smallImgROI, nestedObjects,
- 1.1, 2, 0
- |CASCADE_SCALE_IMAGE,
- Size(30, 30) );
- for ( size_t j = 0; j < nestedObjects.size(); j++ )
- {
- Rect nr = nestedObjects[j];
- center.x = cvRound((r.x + nr.x + nr.width*0.5)*scale);
- center.y = cvRound((r.y + nr.y + nr.height*0.5)*scale);
- radius = cvRound((nr.width + nr.height)*0.25*scale);
- circle( img, center, radius, color, 3, 8, 0 );
- }
- }
- imshow( "result", img );
- }
复制代码
通过不断比较 能够正确识别
得益于rk3399pro的强劲,1296*729 速度还是很快的
换一张人多的
能够一个不漏检测到
`
0
|
|
|
|