opencv learning log 26--detect round holes and mark

foreword

This article focuses on detecting circular holes and marking them in opencv image processing

1. Code

//检测圆孔并且标记
#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);
}

Summarize

1. The code can be run directly, if you don't understand, please leave a message.
2. The material picture is missing, thank you for the follow-up.

Guess you like

Origin blog.csdn.net/taiyuezyh/article/details/122800052
Recommended