我已經下文稱以下鏈接在OpenCV的圖像訓練SVM: Link 1和Link 2爲
從上面我必須設法寫:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/ml/ml.hpp>
using namespace cv;
using namespace std;
int main(){
int num_files = 2;
int width = 128, height = 128;
Mat image[2];
image[0] = imread("Tomato.jpg");
image[1] = imread("Melon.jpg");
Mat new_image(2,height*width,CV_32FC1); //Training sample from input images
int ii = 0;
for (int i = 0; i < num_files; i++){
Mat temp = image[i];
ii = 0;
for (int j = 0; j < temp.rows; j++){
for (int k = 0; k < temp.cols; k++){
new_image.at<float>(i, ii++) = temp.at<uchar>(j, k);
}
}
}
//new_image.push_back(image[0].reshape(0, 1));
//new_image.push_back(image[1].reshape(0, 1));
Mat labels(num_files, 1, CV_32FC1);
labels.at<float>(0, 0) = 1.0;//tomato
labels.at<float>(1, 0) = -1.0;//melon
imshow("New image", new_image);
printf("%f %f", labels.at<float>(0, 0), labels.at<float>(1, 0));
CvSVMParams params;
params.svm_type = CvSVM::C_SVC;
params.kernel_type = CvSVM::LINEAR;
params.gamma = 3;
params.degree = 3;
params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);
CvSVM svm;
svm.train(new_image, labels, Mat(), Mat(), params);
svm.save("svm.xml"); // saving
svm.load("svm.xml"); // loading
Mat test_img = imread("Tomato.jpg");
test_img=test_img.reshape(0, 1);
imshow("shit_image", test_img);
test_img.convertTo(test_img, CV_32FC1);
svm.predict(test_img);
waitKey(0);
}
我得到以下錯誤:
unsupported format or combination of formats, input sample must have 32FC1 type in cvPreparePredictData ...
我遵循第二個鏈接中的所有步驟。所有矩陣都是32FC1類型。 我錯過了什麼? svm參數有問題嗎? 當我嘗試預測結果時,會導致錯誤。
邊評論:您兩次聲明變量I,J和K。一次就夠了(在'for'內) – kebs
有人在這裏發佈了正確的答案,然後刪除了評論。 – purudpd
該問題是由於色彩空間的差異。用灰度讀取文件(imread(「tomato.jpg」,0))修復了它。 – purudpd