本文就把这种用OPENCV_C++编写的实时识别色子点数的算法分享出来
该算法并没有用到上一篇中用到的图像分割算法,距离变换以及分水岭。
(小声的说,其实刚开始是用了,只不过效果很不好,所以就抛弃这两个东西,转而采用了OPENCV基本的形态学分析了)
下面是分析的结果,可以看到,Halcon对于区域的处理真的是强大,OpenCV对区域处理要经过很多繁琐的操作。毕竟在工业上用的比较多的是Halcon LabView 之类的成熟的机器视觉库。
这写基本的算法你们都可以在网上查得到,我直接把它们贴出来就好。
#include <sstream>
#include <iostream>
#include <vector>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
int main()
{
Mat srcImage, grayImg,binaryImg,dst;
vector<vector<Point>>contours;
vector<Vec4i> hierarchy;
Mat dist_8u;
Mat whiteImg(1000, 1000, CV_8UC1, 255);
Mat numberMat;
//int index = 1;
for (int i = 1; i <= 26; i++)
{
srcImage = imread("SrcImg/"+to_string(i) + ".bmp");
cvtColor(srcImage, grayImg, COLOR_BGR2GRAY);
threshold(grayImg, binaryImg, 200, 255, THRESH_BINARY);
findContours(binaryImg, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
for (int i = 0; i < contours.size();i++) {
if (contours[i].size() > 200) {
Mat imgMask = Mat::zeros(1000, 1000, CV_8UC1); //轮廓
//imshow("imgMask1", imgMask);
Mat tempGrayImg;
grayImg.copyTo(tempGrayImg);
drawContours(imgMask, contours, i, Scalar( 255), -1);
bitwise_and(tempGrayImg, imgMask, tempGrayImg);
//imshow("tempGrayImg", tempGrayImg);
threshold(tempGrayImg, tempGrayImg, 180, 255, THRESH_BINARY_INV);
//cout << connectedComponents(tempGrayImg, numberMat) << endl;
putText(srcImage, to_string(connectedComponents(tempGrayImg, numberMat)-2), Point(contours[i][0].x, contours[i][0].y+120), FONT_HERSHEY_PLAIN, 4.0, Scalar(0,255,0), 2);
//参数一目标图像,参数二文本,参数三文本位置,参数四字体类型, 参数五字体大小,参数六字体
}
}
imshow("srcImage", srcImage);
imwrite("E:/" + to_string(i) + ".bmp", srcImage);
int c = waitKey(0);
if (c==27) {
break;
}
}
}
下面是你们可能会用到的数据集,一共有26张照片。
你们也可以自己去拍照片。