# OPENCV——C++版图像形状简单识别

## OPENCV——C++版图像形状简单识别

### 预处理

1.灰度

cvtColor(img, imgGray,COLOR_BGR2GRAY, 0);


2.高斯滤波

GaussianBlur(imgGray, imgBlur, Size(65, 65), 1, 1);


3.Canny边缘检测

		Canny(imgBlur, imgCanny, 40, 120);


4.膨胀

		Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));

dilate(imgCanny, imgDila, kernel);


### 具体代码


#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>

using namespace cv;
using namespace std;

void getcontour(Mat imgDil,Mat img)//判断轮廓
{
vector<vector<Point>> contour;
vector<Vec4i> hierarchy;
findContours(imgDil, contour, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_TC89_KCOS);

vector<vector<Point>> conPoly(contour.size());
vector<Rect> boundRect(contour.size());
for (int i = 0; i < contour.size(); i++)
{
int area = contourArea(contour[i]);//轮廓面积用于排除黑点
cout << area << endl;
string objectType;//形状

if (area > 1000)//排除小黑圆点的干扰
{
float peri = arcLength(contour[i], true);
approxPolyDP(contour[i], conPoly[i], 0.02 * peri, true);//把一个连续光滑曲线折线化
cout << conPoly[i].size() << endl;//边数
boundRect[i] = boundingRect(conPoly[i]);

int objCor = (int)conPoly[i].size();
if (objCor == 3) { objectType = "Tri"; }
else if (objCor == 4) {
float aspRatio = (float)boundRect[i].width / boundRect[i].height;//长宽比来区别正方形与矩形
cout << aspRatio << endl;
if (aspRatio > 0.95 && aspRatio < 1.05) { objectType = "Square"; }
else { objectType = "Rect"; }
}
else if (objCor > 4) { objectType = "Circle"; }
drawContours(img, conPoly, i, Scalar(255, 0, 255), 2);
rectangle(img, boundRect[i].tl(), boundRect[i].br(), Scalar(0.255, 0), 5);//框出图形
putText(img, objectType, { boundRect[i].x,boundRect[i].y - 5 },1,FONT_HERSHEY_PLAIN, Scalar(0, 69, 255), 1);
}
}
}
void main() {
string path = "Resources/shapes.png";
Mat imgGray, imgBlur, imgCanny, imgDila, imgErode;
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
//preprocessing
cvtColor(img, imgGray,COLOR_BGR2GRAY, 0);
GaussianBlur(imgGray, imgBlur, Size(65, 65), 1, 1);
Canny(imgBlur, imgCanny, 40, 120);
dilate(imgCanny, imgDila, kernel);
//灰度->高斯滤波->Canny边缘算法->膨胀
getcontour(imgDila,img);
imshow("Image", img);
//imshow("Image Gray", imgGray);
//imshow("Image Blur", imgBlur);
//imshow("Image Canny", imgCanny);
//imshow("Image dila", imgDila);
waitKey(0);
}


• 13
点赞
• 107
收藏
觉得还不错? 一键收藏
• 2
评论
04-28
04-21 6120
03-09 3458
07-30 250
08-16
02-12
04-09 1770
04-07 2万+
03-30 3859

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。