首页 > 解决方案 > 即使检测到人脸并正确获取左右两半,OpenCV 也没有检测到眼睛

问题描述

我试图在我的代码中找到问题并理解与 opencv 和面部/眼睛检测相关的问题。完整代码在这里:

https://pastebin.com/s4zCN7gM

代码块中的代码是问题所在的浓缩(比较)。

//Search for both eyes within the given face image. Returns the eye centers in 'leftEye' and 'rightEye',
// or sets them to (-1,-1) if each eye was not found. Note that you can pass a 2nd eyeCascade if you
// want to search eyes using 2 different cascades. For example, you could use a regular eye detector
// as well as an eyeglasses detector, or a left eye detector as well as a right eye detector.
// Or if you don't want a 2nd eye detection, just pass an uninitialized CascadeClassifier.
// Can also store the searched left & right eye regions if desired.
void detectBothEyes(const Mat &face, CascadeClassifier &eyeCascade1, 
                                     CascadeClassifier &eyeCascade2, 
                                     Point &leftEye, Point &rightEye, 
                                     Rect *searchedLeftEye, 
                                     Rect *searchedRightEye,
                                     String filename) {


  //For default eye.xml or eyeglasses.xml: Finds both eyes in 
  // roughly 40% of detected faces, but does not detect closed eyes.
  const float EYE_SX = 0.16f;
  const float EYE_SY = 0.26f;
  const float EYE_SW = 0.30f;
  const float EYE_SH = 0.28f;

  int leftX = cvRound(face.cols * EYE_SX);
  int topY = cvRound(face.rows * EYE_SY);
  int widthX = cvRound(face.cols * EYE_SW);
  int heightY = cvRound(face.rows * EYE_SH);
  int rightX = cvRound(face.cols * (1.0-EYE_SX-EYE_SW) );  //Start of right-eye corner

  Mat topLeftOfFace = face(Rect(leftX, topY, widthX, heightY));
  Mat topRightOfFace = face(Rect(rightX, topY, widthX, heightY));
  Rect leftEyeRect, rightEyeRect;

  imwrite(filename + "_leftHalfFace.png",topLeftOfFace); 
  imwrite(filename + "_rightHalfFace.png",topRightOfFace); 

  //Search the left region, then the right region using the 1st eye detector.
  detectLargestObject(topLeftOfFace, eyeCascade1, leftEyeRect, 
                      topLeftOfFace.cols);
  cout << "leftEyeRect= "<< endl << " " << leftEyeRect << endl << endl;
  detectLargestObject(topRightOfFace, eyeCascade1, rightEyeRect, 
                      topRightOfFace.cols);
  cout << "rightEyeRect= "<< endl << " " << rightEyeRect << endl << endl;

  //NOTE...there is code here that says if leftEyeRect or rightEyeDetect was not 
  // detected to set
  // to (-1,-1)

}

代码是c++。该代码是从一本书中提供的示例代码修改而来的。

我正在尝试读取图像并检测面部和眼睛(以及面部识别)。在我尝试检测的 20 张图像(10 张汤姆克鲁斯和 10 张艾玛沃特森)上,人脸检测似乎始终成功。但是,即使我能够成功地将检测到的人脸分成左右两半(每一半都显示适当的眼睛),眼睛检测对于几张图像都失败了。我不明白为什么以及我能做些什么来解决这个问题?

具体问题出在函数 detectBothEyes 中,其中变量 leftEyeRect 和 rightEyeRect 都返回 (-1, -1)(意味着它没有找到眼睛)。

谁能指出我的问题或如何改善对眼睛的检测?

https://pastebin.com/s4zCN7gM

我希望检测到眼睛,因此变量“leftEyeRect”和“rightEyeRect”不是(-1,-1)而是正值)。

标签: c++opencv

解决方案


推荐阅读