我正在尝试测试OpenCV中的面部识别API。我已经导入了.jar
提供的文件,它可以正确加载DLL。该imageLibIit()
函数将加载DLL。我还在目录中提供了提供的XML文件:
src \ main \ resources \ opencv
public boolean faceDetect(String inputFilename, String outputFilename){
if(!loaded){
if(!imageLibInit()){ // initializes and loads the dynamic libraries
return false;
}
}
//TODO @Austin fix image resource issues
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String xmlResource = loader.getResource("opencv/haarcascade_frontalface_alt.xml").getPath();
CascadeClassifier faceDetector = new CascadeClassifier(xmlResource);
Mat inputImage = Imgcodecs.imread(inputFilename);
ErrorUtils.println(xmlResource);
if(inputImage.empty()){
ErrorUtils.println("image is empty");
return false;
}
MatOfRect facesDetected = new MatOfRect();
faceDetector.detectMultiScale(inputImage, facesDetected);
Rect[] detections = facesDetected.toArray();
ErrorUtils.println("Faces detected in '" + inputFilename + "': " + detections.length);
for(Rect detection : detections){
Imgproc.rectangle(
inputImage,
new Point(detection.x, detection.y),
new Point(detection.x + detection.width, detection.y + detection.height),
new Scalar(0, 0, 255)
);
}
Imgcodecs.imwrite(outputFilename, inputImage);
return true;
}
我仍然遇到错误:
OpenCV Error: Assertion failed (!empty()) in cv::CascadeClassifier::detectMultiScale, file C:\builds\master_PackSlaveAddon-win64-vc12-static\opencv\modules\objdetect\src\cascadedetect.cpp, line 1639
我研究了此错误,每次解决方案似乎都与资源有关。这很可能是一个非常简单的问题,但到目前为止,我仍然受困。
查看OpenCV源代码,我们可以找到以下内容:
由于resouce loader("/D:/Programming/workspaces/github/project1/HomeServer/target/classes/opencv/haarcascade_frontalface_alt.xml"
)返回的路径有点奇怪,包含前导斜杠,因此第一个怀疑会导致打开文件时出现问题。
我编写了一个简单的小测试以使用Visual C ++进行检查:
#include <cstdio>
#include <iostream>
bool try_open(char const* filename)
{
FILE* f;
f = fopen(filename, "rb");
if (f) {
fclose(f);
return true;
}
return false;
}
int main()
{
char const* path_1("/e:/foo.txt");
char const* path_2("e:/foo.txt");
std::cout << "fopen(\"" << path_1 << "\") -> " << try_open(path_1) << "\n";
std::cout << "fopen(\"" << path_2 << "\") -> " << try_open(path_2) << "\n";
return 0;
}
输出:
fopen("/e:/foo.txt") -> 0
fopen("e:/foo.txt") -> 1
因此,路径是罪魁祸首。根据此答案,一种与平台无关的方法是如下修改代码以生成有效路径:
// ...
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String xmlResource = loader.getResource("opencv/haarcascade_frontalface_alt.xml").getPath();
File file = new File(xmlResource);
xmlResource = file.getAbsolutePath());
// ...
CascadeClassifier faceDetector = new CascadeClassifier(xmlResource);
if(faceDetector.empty()){
ErrorUtils.println("cascade classifier is empty");
return false;
}
// ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句