source: gs3-extensions/openCV/trunk/src/src/FaceFinder-jan2013/facefinder.cpp@ 26880

Last change on this file since 26880 was 26880, checked in by davidb, 11 years ago

Code by Joshua Holland, based on openCV, to do facial recognition. Outputs GIMP image with layers: base photo, black-out circles, and a final layer which is the merging of the two. The co-ord of the detected faces (x,y,width,height) are also output as a JSON file

File size: 2.5 KB
RevLine 
[26880]1#include <opencv2/opencv.hpp>
2#include <opencv2/core/core.hpp>
3#include <opencv2/highgui/highgui.hpp>
4#include <iostream>
5#include <stdio.h>
6
7using namespace std;
8using namespace cv;
9
10CascadeClassifier face_cascade;
11
12void detectFacialFeatures(Mat frame, Mat face_image, char* img_no)
13{
14 std::vector<Rect> faces;
15 Mat frame_gray;
16
17
18 cvtColor( frame, frame_gray, CV_BGR2GRAY );
19 equalizeHist( frame_gray, frame_gray );
20
21 //-- Detect faces
22 face_cascade.detectMultiScale( frame_gray, faces, 1.2, 2, 0|CV_HAAR_SCALE_IMAGE);
23 printf("\"count\":%i, \"faces\":[",faces.size());
24 for( int i = 0; i < faces.size(); i++ )
25 {
26 if (i > 0)
27 {
28 printf(",");
29 }
30 printf("{ \"x\":%i, \"y\":%i, \"width\":%i, \"height\":%i }",faces[i].x, faces[i].y, faces[i].width, faces[i].height);
31 ellipse( face_image,
32 Point( faces[i].x + (faces[i].width / 2), faces[i].y + (faces[i].height / 2) ),
33 Size( faces[i].width / 2, faces[i].height / 2 ),
34 0,
35 0,
36 360,
37 Scalar( 0, 0, 0, 255),
38 -1,
39 8 );
40
41 }
42 printf("]");
43}
44
45int main( int argc, char** argv )
46{
47 if (argc < 3)
48 {
49 printf("Usage: %s <Path to OpenCV> <Path to image 1> ... <Path to image n>\n", argv[0]);
50 return 1;
51 }
52 Mat img;
53 std::string cascadeloc = std::string(argv[1]) + "/share/OpenCV/haarcascades/haarcascade_frontalface_alt2.xml";
54
55 if( !face_cascade.load(cascadeloc) )
56 { printf("--(!)Error loading Face Cascade\n"); return -1; };
57 printf("{");
58 printf("\"count\":%i, \"files\":[",argc-2);
59 for (int i = 2; i < argc; i++)
60 {
61 if (i > 2) { printf(",");}
62 printf ("{");
63 img = imread(argv[i], CV_LOAD_IMAGE_COLOR);
64 printf("\"file\":\"%s\",",argv[i]);
65 if (!img.empty())
66 {
67 Mat face_image(img.rows, img.cols, CV_8UC4, Scalar(0,0,0,0));
68 detectFacialFeatures(img, face_image, argv[i]);
69 std::string s = argv[i];
70 replace(s.begin(), s.end(), '.', '-');
71 if (!face_image.empty())
72 {
73 imwrite( s + std::string("-faces.png"), face_image );
74 std::string cmd = "composite " + s + "-faces.png " + argv[i] + " " + s + "-merged.jpg";
75 system(cmd.c_str());
76 }
77 else
78 {
79 fprintf(stderr, "File '%s' didn't seem to capture any faces... Not Saving Faces Image\n", argv[i]);
80 }
81 }
82 else
83 {
84 printf("\"error\":\"File Doesn't exist, or isn't an image.\"");
85 }
86 printf("}");
87 }
88 printf("]}");
89
90 return 0;
91}
Note: See TracBrowser for help on using the repository browser.