前偏讲的是0-255的二值图像,Blob 是对灰度图像的检测。
可根据面积、阈值、圆度、椭圆、凹凸性进行图像的过滤。
实现步骤:
//1.载入图片
//2.设置检测参数
//3.把检测的内容放入keyPoint中
//4.画圆
上代码:
Mat img = imread("D:/OpenCVPrj/WangYi/MOpenCV_class4/images/blob_detection.jpg", IMREAD_GRAYSCALE);
imshow("input", img);
// Set up detector with default parameters
//Ptr<SimpleBlobDetector> detector = SimpleBlobDetector::create();
// Setup SimpleBlobDetector parameters.
SimpleBlobDetector::Params params;
// Change thresholds
params.minThreshold = 10;
params.maxThreshold = 200;
// Filter by Area.
params.filterByArea = true;
params.minArea = 50;
// Filter by Circularity
//params.filterByCircularity = true;
//params.minCircularity = 0.1;
Filter by Convexity
//params.filterByConvexity = true;
//params.minConvexity = 0.87;
Filter by Inertia
//params.filterByInertia = true;
//params.minInertiaRatio = 0.01;
Ptr<SimpleBlobDetector> detector = SimpleBlobDetector::create(params);
//检测完的内容就在keypoints
std::vector<KeyPoint> keypoints;
detector->detect(img, keypoints);
// Mark blobs using image annotation concepts we have studied so far
int x, y;
int radius;
double diameter;
cvtColor(img, img, COLOR_GRAY2BGR);
for (int i = 0; i < keypoints.size(); i++)
{
//圆心的位置
KeyPoint k = keypoints[i];
Point keyPt;
keyPt = k.pt;
x = (int)keyPt.x;
y = (int)keyPt.y;
// Mark center in BLACK
circle(img, Point(x, y), 5, Scalar(255, 0, 0), -1);
//得到直径和半径 Get radius of coin
diameter = k.size;
radius = (int)diameter / 2.0;
// Mark blob in GREEN
circle(img, Point(x, y), radius, Scalar(0, 255, 0), 2);
}
imshow("Image", img);
waitKey(0);