// openCVを使った顔検出 #include "opencv2/objdetect/objdetect.hpp" #include "opencv/highgui.h" #include "opencv2/imgproc/imgproc.hpp" #include "opencv/cv.h" #include "iostream" #include "stdlib.h" #include "fstream" using namespace cv; int main(int argc, char **argv) { IplImage *src_img=0, *src_gray=0; if (argc < 2 || (src_img = cvLoadImage (argv[1], CV_LOAD_IMAGE_COLOR)) == 0) return -1; src_gray = cvCreateImage (cvGetSize (src_img), IPL_DEPTH_8U, 1); CvMemStorage *storage = 0; storage = cvCreateMemStorage (0); cvClearMemStorage (storage); cvCvtColor (src_img, src_gray, CV_BGR2GRAY); cvEqualizeHist (src_gray, src_gray); CvMemStorage* FaceStorage = cvCreateMemStorage(0); CvHaarClassifierCascade* FaceCascade = (CvHaarClassifierCascade*) cvLoad("/opt/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt_tree.xml"); std::ofstream out_file("DetectedFace.out"); out_file<<"xMin,"<<"yMin,"<<"xMax,"<<"yMax"<<'\n'; cvClearMemStorage( FaceStorage ); CvSeq* FaceObjects = cvHaarDetectObjects(src_img,FaceCascade,FaceStorage,1.1,4,0, cvSize( 30, 30 )); CvRect* rF; // detect at most 10 faces int n=std::min(10,(FaceObjects ? FaceObjects->total : 0 )); for (int i=0;i<n;++i){ rF = ( CvRect* )cvGetSeqElem( FaceObjects, i ); out_file<<rF->x<<","<< rF->y<<","<<rF->x+rF->width<<","<<rF->y+rF->height<<'\n'; } cvReleaseImage(&src_img); cvReleaseImage(&src_gray); return 0; }
# 上のopenCVのプログラムをRで使用する関数 JoFaceDetection<-function(file_name) { res<-system(paste("./JoFaceDetect ",file_name)) if (res!=0) { warning("incorrect file name"); return(-99) } else { xys=read.csv("DetectedFace.out"); if (nrow(xys)!=0) { print("successfully detected face(s)"); return(xys); } else { print("no face was detected"); return(-99); } } }
実行例
loc<-JoFaceDetection("~/Downloads/IMG_2095.jpg") [1] "successfully detected face(s)" > loc xMin yMin xMax yMax 1 307 114 521 328