This code aims to binarize an image, detect the blobs in the image, label the regions of interest (ROI), and draw a rectangle around the ROI.
#include "opencv2/opencv.hpp"
#include <iostream>
#define IMAGE_PATH "test2.bmp"
#define COLOR_IMAGE_WINDOW_NAME "color image"
#define GRAY_IMAGE_WINDOW_NAME "gray image"
using namespace cv;
using namespace std;
int main()
{
Mat src = imread("test1.bmp", IMREAD_GRAYSCALE);
Mat binary;
threshold(src, binary, 128, 255, THRESH_BINARY);
vector<KeyPoint> keypoints;
SimpleBlobDetector::Params params;
params.filterByArea = true;
params.minArea = 100;
params.maxArea = 10000;
params.filterByCircularity = true;
params.minCircularity = 0.1;
params.filterByConvexity = true;
params.minConvexity = 0.87;
params.filterByInertia = true;
params.minInertiaRatio = 0.01;
Ptr<SimpleBlobDetector> detector = SimpleBlobDetector::create(params);
detector->detect(binary, keypoints);
Mat labeledImage;
Mat labelStats;
Mat labelCentroids;
int nLabels = connectedComponentsWithStats(binary, labeledImage, labelStats, labelCentroids);
Rect roi(10, 10, 100, 100);
Mat roiImage = src(roi);
rectangle(src, roi, Scalar(255, 0, 0), 2);
imshow("binary", binary);
imshow("src", src);
waitKey(0);
destroyAllWindows();
return 0;
}
This code binarizes an image using the threshold()
function, detects blobs in the binary image using the SimpleBlobDetector()
function, labels regions of interest (ROI) with connectedComponentsWithStats()
, and draws a rectangle around the ROI.