我正在尝试在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
我已经研究过这个错误,每次解决方案似乎与资源有关。这可能是一个非常简单的问题,但我现在陷入困境。
答案 0 :(得分:1)
检查OpenCV源代码,我们可以找到以下内容:
由于资源加载器("/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
因此道路是罪魁祸首。根据{{3}},一种独立于平台的方法是按如下方式修改代码以生成有效路径:
// ...
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;
}
// ...