OpenCV案例(二):选取圆对象

      OpenCV提供了一些基本的形态学处理方法与绘图操作,比如膨胀、腐蚀、开闭操作、画圆,画椭圆,画线,画矩形,在图像里插入文字等功能。

代码:

#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <math.h>
#include <iostream>

using namespace std;
using namespace cv;

//double threshold = 200.0;
Mat BinaryImg,morhImage;

int main()
{

	Mat img = imread("../img/33.png", IMREAD_GRAYSCALE);
	imshow("原图", img);

	threshold(img , BinaryImg ,0 ,255,THRESH_BINARY |THRESH_OTSU);
	imshow("二值化",BinaryImg);

	//形态学处理
	Mat kernel = getStructuringElement(MORPH_RECT, Size(4, 4));
	morphologyEx(BinaryImg, morhImage, MORPH_OPEN, kernel);  //去掉杂点
	imshow("形态学结果", morhImage);

	vector<vector<Point>> contours;
	Mat resutimg = Mat::zeros(img.size(),CV_8UC3);
	findContours(morhImage, contours, RETR_TREE, CHAIN_APPROX_SIMPLE);   //找到图像轮廓
	for (int i = 0; i < contours.size(); i++)
	{
		double area = contourArea(contours[i]);   //去掉小区域
		if(area < 100 ) continue;
		Rect rect = boundingRect(contours[i]);     //根据外轮廓长宽比率寻找圆
		float ratio = (float)(rect.width) / rect.height;
		if (ratio > 0.9 && ratio < 1.1)
		{
			drawContours(resutimg, contours, i, Scalar(0, 0, 250),-1); //找到圆的轮廓,-1代表填充
		
			int x = rect.x + rect.width / 2;
			int y = rect.y + rect.height / 2;
			//circle(resutimg, Point(x, y), 2, Scalar(0, 0, 250),2);  //画小圆点
			cout << "circle area : " << area << endl;
			cout << "circle length : " << arcLength(contours[i], true);
			cout << "circle center : x= " << x<<" , y = "<< y << endl;
		}
	}

	imshow("result", resutimg);   //绘制圆的轮廓与圆心
	waitKey(0);
}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值