cvPreparePredictData中不支持的格式或格式组合(输入样本必须具有32fC1类型)

Unsupported format or combination of formats (Input sample must have 32fC1 type) in cvPreparePredictData

本文关键字:格式 样本 类型 32fC1 输入 不支持 组合 cvPreparePredictData      更新时间:2023-10-16

我试图训练我自己的SVM来检测人,我将图像序列全部调整为320x240。我在训练过程中将图像转换为灰色,在测试过程中将测试图像转换为灰度,但我出现了错误。

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv/cv.h>
#include <iostream>
#include <vector>
#include <stdio.h>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/nonfree/features2d.hpp>
#include <fstream>
using namespace std;
using namespace cv;
int main(int argc, char* argv[]) {
String folder = "output/*.jpg";
vector<String> filenames;
glob(folder, filenames);
Mat gray,gray1;
int img_area=320*240;
Mat training_mat(filenames.size(),img_area,CV_32FC1);
Mat labels(filenames.size(),1,CV_32FC1);
for(int i = 0; i < 900; i++){
labels.at<float>(i,0)=1;
}
for(int i = 900; i < filenames.size(); i++){
labels.at<float>(i,0)=-1;
}
for (size_t i = 0; i < filenames.size(); ++i){
Mat img = imread(filenames[i]);
cvtColor(img, gray, CV_RGB2GRAY);
int ii = 0; 
for (int k = 0; k < gray.rows; k++) {
for (int j = 0; j < gray.cols; j++) {
training_mat.at<float>(i,ii++) = gray.at<uchar>(k,j);
}
}
}
CvSVMParams params;
params.svm_type = CvSVM::C_SVC;
params.kernel_type = CvSVM::POLY;
params.gamma = 3;
params.degree = 3;
CvSVM svm;
svm.train(training_mat, labels, Mat(), Mat(), params);
svm.save("svm_filename"); // saving
svm.load("svm_filename"); // loading
Mat image = imread("output/500.jpg");
cvtColor(image, gray1, CV_RGB2GRAY);
int response = svm.predict(gray1);
if(response == 1){
cout << "person " << endl ;
}
return 0;
}

我编译的程序我得到了这个错误:

OpenCV错误:在cvPreparePredictData,file/home/mourad/occv/opencv2.4.10/modules/ml/src/inner_functions.cpp中,抛出"cv::Exception"实例后调用的1102行终止不支持的格式或格式组合(输入样本必须具有32fC1类型)

您也应该将gray1转换为32FC1

cvtColor(image, gray1, CV_RGB2GRAY);
gray1.convertTo(gray1, CV_32FC1, 1.0/255.0); // <-- add this line before predict
int response = svm.predict(gray1);

此外,请注意,下面的代码不是从uchar转换为float的正确方法,因为它们应该使用不同的范围:[0,255][0,1]

training_mat.at<float>(i,ii++) = gray.at<uchar>(k,j);

我在我的程序中添加了这个:

cvtColor(image,gray1, CV_RGB2GRAY);
Mat image_mat(1,img_area,CV_32FC1);
int jj=0;
for (int k = 0; k < gray1.rows; k++) {
for (int j = 0; j < gray1.cols; j++) {
image_mat.at<float>(0,jj++) = gray.at<uchar>(k,j);
}
}
int response=svm.predict(image_mat);
if(response == 1){
cout << "person detected" << endl;
}

但程序运行时没有显示任何内容。