opencv svm 識別自己寫的手寫數字
int main()
{
Mat src, gray,medblurImg,threImg;
Mat structElem,eroImg,dilateImg,cannyImg;
src = imread("test.jpg");
cvtColor(src, gray, CV_RGB2GRAY);
medianBlur(gray, medblurImg, 3);
threshold(medblurImg, threImg, 100, 255, CV_THRESH_BINARY_INV);
structElem = getStructuringElement(CV_SHAPE_RECT, Size(3,3));
dilate(threImg, dilateImg, structElem);
erode(dilateImg, eroImg, structElem);
//imshow("dilateImg", eroImg); waitKey(0);
Mat contourImg = Mat::zeros(eroImg.size(),CV_8UC3);
Mat testData = Mat::zeros(11,784, CV_32FC1);
vector<vector<Point>> contours;
findContours(eroImg, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
vector<Rect> numRect;
int testDataRow = 0;
int addpixel = 10;
for (int i = 0; i < contours.size(); i++)
{
Rect tempRect = boundingRect(contours.at(i));
tempRect.x = tempRect.x - addpixel;
tempRect.y = tempRect.y - addpixel;
tempRect.width = tempRect.width + addpixel*2;
tempRect.height = tempRect.height + addpixel*2;
numRect.push_back(tempRect);
Mat num = eroImg(tempRect);
resize(num, num, Size(28, 28));
threshold(num, num, 1, 255, CV_THRESH_BINARY);
int testDataCol = 0;
for(int j = 0;j<num.rows;j++)
for (int k = 0; k < num.cols; k++)
{
float t = (float)num.at<uchar>(j,k);
testData.at<float>(testDataRow, testDataCol) = t;
testDataCol++;
}
testDataRow++;
char winname[50] = {};
_itoa(i, winname, 10);
namedWindow(winname, 0); imshow(winname, num); waitKey(0);
}
testData = testData / 255;
// //------------------------ 5. load the svm ----------------------------------------------------
std::cout << "開始匯入SVM檔案...\n";
Ptr<SVM> svm1 = StatModel::load<SVM>("mnist_svm.xml");
std::cout << "成功匯入SVM檔案...\n";
for (int i = 0; i < testData.rows; i++) {
Mat sample = testData.row(i);
float res = svm1->predict(sample);
std::cout << res;
}
//drawContours(contourImg, contours, -1, Scalar(0, 255, 0));
//imshow("contours", contourImg); waitKey(0);
cin.get();
return 0;
}