[英]OpenCV Assertion Error in detectMultiScale
我正在嘗試測試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源代碼,我們可以找到以下內容:
由於資源加載程序返回的路徑( "/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;
}
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.