opencv的blob分析找圆(C++)

opencv的blob分析找圆(C++)

实现目的

对于一些定位场景,产品上有圆形Mark点,怎么使用免费的opencv算法库取代商用的halcon算法库,下面让我们一起看看实现的过程。

效果图在这里插入图片描述## 代码实现```

// C++


#include <opencv2/opencv.hpp>
#include <iostream>
#include <cstring>
#include <windows.h> 
using namespace std;
using namespace cv;
// 全局变量
Mat srcImage;
Mat dstImage;
Mat binImage;
int thresholdValue =176;
// 算法
void ChangeThresholdValue(int , void*)
//void ChangeThresholdValue()
{
	double start = GetTickCount();
	dstImage = srcImage.clone();
	threshold(dstImage, binImage, thresholdValue,255, THRESH_BINARY_INV);
	vector<vector<Point>> contours;
	cvtColor(binImage, binImage, COLOR_BGR2GRAY);
	findContours(binImage,contours,RETR_TREE,CHAIN_APPROX_SIMPLE);
	
	system("cls");
	for (int i=0;i<contours.size();++i)
	{
		RotatedRect rotateRect = cv::minAreaRect(contours[i]);//轮廓最小外接矩形
		Point pnt = Point(rotateRect.center.x, rotateRect.center.y);//最小外接矩形的中心点坐标
		string info;
		double area = contourArea(contours[i]);
		double rudis = sqrt(area / CV_PI);
		double length = arcLength(contours[i],true);
		double round = 4 * CV_PI*area / length / length;
		info = to_string((int)area)+"\\"+ DoubleToString(round, 2);
		DoubleToString(round,1);			
		if (round>0.85&& area>700)
		{
			drawContours(dstImage, contours, i, Scalar(0, 255, 0));
			putText(dstImage, info, pnt, FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255), 0.2, 0.2);
			//绘制横线
			cv::line(dstImage, cv::Point2d(pnt.x - rudis / 2, pnt.y), cv::Point2d(pnt.x + rudis / 2, pnt.y),Scalar(0, 0, 255), 1, cv::LINE_AA, 0);
			//绘制竖线
			cv::line(dstImage, cv::Point2d(pnt.x, pnt.y - rudis / 2), cv::Point2d(pnt.x, pnt.y + rudis / 2), Scalar(0, 0, 255), 1, cv::LINE_AA, 0);
		}		
	}
	double end = GetTickCount();
	cout << "算法耗时" << end-start <<  "ms" << endl;
	imshow("blob", dstImage);
}

// main函数

int main()
{
	namedWindow("blob", WINDOW_GUI_NORMAL);
	srcImage = imread("./blob2.jpg");
	if (srcImage.empty())
	{
		cout << "not load image..." << endl;
	}	
	createTrackbar("阈值", "blob", &thresholdValue, 255, ChangeThresholdValue, 0);	
	waitKey(0);

}
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值