opencv学习笔记四十八:对象提取

案例背景:找到下图中的圆进行定位,并计算其面积和周长。

方案思路:先灰度化再二值化,再进行开操作去除杂点,寻找轮廓,通过轮廓特征找到圆部分。 

#include<opencv2\opencv.hpp>
using namespace cv;
using namespace std;
int main(int arc, char** argv) { 
	Mat src = imread("1.jpg");
	namedWindow("input", CV_WINDOW_AUTOSIZE);
	imshow("input", src);
	//灰度化
	Mat gray;
	cvtColor(src, gray, CV_BGR2GRAY);
	//二值化
	Mat binaryImg;
	threshold(gray, binaryImg, 0, 255, THRESH_BINARY | THRESH_OTSU);
	//开操作
	Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
	morphologyEx(binaryImg, binaryImg, MORPH_OPEN, kernel);
	//寻找轮廓
	vector<vector<Point>>contours;
	vector<Vec4i>hierarchy;
	findContours(binaryImg, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
	for (int i = 0; i < contours.size(); i++) {
		Rect rect = boundingRect(contours[i]);
		float area = contourArea(contours[i]);
		float length = arcLength(contours[i],true);
		if (area < 100) continue;//面积过滤
	    Point2f center;
		float radius;
		float ratio = float(rect.width) / float(rect.height);//长宽比过滤
		if (ratio<1.1 && ratio > 0.9) {
			minEnclosingCircle(contours[i],center,radius);
			circle(src, center,radius, Scalar(0, 0, 255), -1);
			circle(src, center, 2, Scalar(0, 255, 0), 2);
			printf("area:%f\n", area);
			printf("length:%f\n",length);
		}
	}
	imshow("out", src);
	waitKey(0);
	return 0;
}

 

猜你喜欢

转载自blog.csdn.net/qq_24946843/article/details/82767315