前言
这篇文章主要讲述opencv图像处理中的检测圆孔并且标记
一、代码
//检测圆孔并且标记
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
cv::Mat dst;
cv::Mat dstbin;
cv::Mat dsttemp;
cv::Mat finalpicture;
cv::Mat src = imread("C://Users//john//Desktop//1.jpg");
cv::Mat srcgray = imread("C://Users//john//Desktop//1.jpg", 0);
threshold(srcgray, dstbin, 100, 255, THRESH_OTSU); //大津法
src.copyTo(dst);
bitwise_not(dstbin, dsttemp);
vector<vector<Point>> contours;
vector<Vec4i> hirearchy;
findContours(dsttemp, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
int num = contours.size();
cout << num << endl;
for (int i = 0; i < num; i++)
{
//RotatedRect rbox = minAreaRect(contours[i]);
//cv::Point2f vtx[4];
//rbox.points(vtx);
//cout << vtx << endl;
//if((vtx[0].x-vtx[1].x) + (vtx[0].y - vtx[1].y) ^ 2)
//cout << contours[i] << endl;
float area = contourArea(contours[i]);//计算轮廓面积
float len = arcLength(contours[i], true);//计算轮廓周长
float roundness = (4 * CV_PI * area) / (len * len);//圆形度
// cout << area << endl;
if (roundness > 0.5&&area>=100)
{
drawContours(dst, contours, i, Scalar(255, 0, 0), -1, 8);
}
//drawContours(dst,contours, i, Scalar(255, 255, 255),-1,8, InputArray hierarchy = noArray(), int maxLevel = INT_MAX, Point offset = Point())
}
cv::imshow("dsttemp", dsttemp);
cv::imshow("dst", dst);
//cv::imshow("src", src);
//cv::imshow("dsttemp", dsttemp);
waitKey(0);
}
总结
1.代码可以直接运行,如果有不懂得请留言哦。
2.缺少素材图片,后续补上谢谢。