OpenCV 버전 : 2.4.10

 

- CAM으로부터 프레임을 받아서 얼굴 검출하여 얼굴에 사각형 그리고 출력하는 코드

 

#include "opencv/cv.h"
#include "opencv/highgui.h"
#include <iostream>

 

using namespace std;
using namespace cv;

int _tmain(int argc, _TCHAR* argv[])
{

// 비디오 프레임 생성
 VideoCapture capture(0);

 if (!capture.isOpened()) {
  cerr << "Could not open camera" << endl;
  return 0;
 }

 // 윈도우 창 생성
 namedWindow("webcam", 1);

 // Haarcascade 로드
 CascadeClassifier face_classifier;
 face_classifier.load("c:/haarcascade_frontalface_alt.xml");

 while (true)
 {
  bool frame_valid = true;

  Mat frame_original; // 프레임 원본 Mat
  Mat frame; // 결과 프레임 Mat

  try {
   capture >> frame_original; // get a new frame from webcam
   resize(frame_original, frame, Size(frame_original.cols / 2, frame_original.rows / 2), 0, 0, CV_INTER_NN);
  }
  catch (Exception& e) {
   cerr << "Exception occurred. Ignoring frame..." << e.err << endl;
   frame_valid = false;
  }

  if (frame_valid) {
   try {
    // 그레이스케일 영상으로 변환, 히스토그램 평준화 수행
    Mat grayframe;
    cvtColor(frame, grayframe, CV_BGR2GRAY);
    equalizeHist(grayframe, grayframe);

    // 얼굴 검출(FD)

    // vector에 검출된 얼굴 저장
    vector<Rect> faces;

    face_classifier.detectMultiScale(grayframe, faces, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_SCALE_IMAGE, Size(30, 30));

    // 얼굴에 사각형 그리기
    for (int i = 0; i < faces.size(); i++) {
     Point lb(faces[i].x + faces[i].width, faces[i].y + faces[i].height);
     Point tr(faces[i].x, faces[i].y);

     rectangle(frame, lb, tr, Scalar(0, 255, 0), 3, 4, 0);
    }

    // 출력
    imshow("webcam", frame);
   }
   catch (Exception& e) {
    cerr << "Exception occurred. Ignoring frame..." << e.err << endl;
   }
  }
  if (waitKey(30) >= 0) break;
 }

 return 0;
}

+ Recent posts