#include <stdio.h>
#include <time.h>
#include <opencv2/opencv.hpp>
#include <opencv/cv.h>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/ml/ml.hpp>
#include <io.h>
using namespace std;
using namespace cv;
using namespace ml;
int main()
{
VideoCapture capture(0);
string modelpath = "G:\数字识别\svm.xml";
Ptr<SVM> svm = StatModel::load<SVM>(modelpath);
while (1)
{
Mat img;
capture >> img;//读取当前帧
vector<vector<Point>> contours;//点容器的容器,用于存放轮廓的点的容器的容器
vector<Vec4i> hierarchy;//点的指针容器
Mat dst, tmp;
img.copyTo(dst);
cvtColor(dst, dst, COLOR_RGB2GRAY);
blur(dst, dst, Size(3, 3));
//GaussianBlur(dst, dst, Size(3, 3), 0.5, 0.5);
//medianBlur(dst, dst, 3);
threshold(dst, tmp, 120, 255, CV_THRESH_BINARY_INV);
findContours(tmp, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
vector<vector<Point>>::iterator It;
int sum = 1;
for (It = contours.begin(); It < contours.end(); It++)
{
Rect rect = boundingRect(*It);
double weigth = rect.br().x - rect.tl().x;//宽
double height = rect.br().y - rect.tl().y;//高
if ((weigth < height) && (height > 50))
{
rectangle(img, rect, Scalar(0, 15, 255), 2);
Mat inMat;
Mat roi = img(rect);
cvtColor(roi, inMat, COLOR_RGB2GRAY);
namedWindow("hhhh", 0);
imshow("hhhh", roi);
resize(inMat, inMat, Size(8, 16), (0, 0), (0, 0), INTER_AREA);
Mat p = inMat.reshape(1, 1);
p.convertTo(p, CV_32FC1);
int response = (int)svm->predict(p);
char result[20];
sprintf_s(result, "result:%d", response);
putText(img, result, Point(0, 30 * (sum++)), 2, 1, CV_RGB(25, 200, 25));
}
}
if (waitKey(1) >= 0)break;//延时30ms
imshow("bug", img);
}
return 0;
}