BlobDetector的使用与参数说明(OpenCV/C++)

通过opencv的BlobDetector方法可以检测斑点、圆点、椭圆等形状

以下是使用方式及代码说明:

1、导入必要的OpenCV库和头文件。

#include <opencv2/opencv.hpp>
#include <opencv2/blob/blobdetector.hpp>

2、读取图像并将其转换为灰度图像。  

cv::Mat image = cv::imread("image.jpg", cv::IMREAD_GRAYSCALE);

3、创建一个BlobDetector对象,并设置相关参数。

cv::SimpleBlobDetector::Params params;

// 设置检测圆的灰度阈值范围:默认0~255
params.minThreshold = 0;
params.maxThreshold = 255;

//设置识别的预期颜色
//params.blobColor = 0;    //0表示预期检测圆的颜色为白色,一般不用

// 用于过滤面积小的blob
params.filterByArea = true;    //true表示启动该功能,false表示关闭该功能,下述相同
params.minArea = 50;            //单位是圆的像素面积,即圆所占的像素点数
params.maxArea = 1000;        //一定要写maxArea

//用于过滤不符合圆形形状的blob
params.filterByCircularity = true;
params.minCircularity = 0.8;

//用于过滤不规则或者非凸的blob
params.filterByConvexity = true;
params.minConvexity = 0.8;

//用于过滤不符合椭圆形状的blob
params.filterByInertia = true;
params.minInertiaRatio = 0.8;

// 创建BlobDetector对象
cv::Ptr<cv::SimpleBlobDetector> detector = cv::SimpleBlobDetector::create(params);

4、使用BlobDetector在图像中检测圆形。

std::vector<cv::KeyPoint> keypoints;
detector->detect(image, keypoints);

5、绘制检测到的圆。

cv::Mat imageWithKeypoints;
cv::drawKeypoints(image, keypoints, imageWithKeypoints, cv::Scalar(0, 0, 255), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);

6、显示并保存带有检测到的圆的图像。

cv::imshow("Circle Detection", imageWithKeypoints);
cv::waitKey(0);
cv::imwrite("result.jpg", imageWithKeypoints);

猜你喜欢

转载自blog.csdn.net/qq_19319481/article/details/134014925