Reputation: 762
Okay, so I'm trying openCV with c++, and I want to do a simple detection program for objects that are black colored. So I have this simple code:
int main()
{
Mat3b bgr = imread("C:/Users/sesoa/Desktop/photos/shapes.png");
Mat3b hsv;
cvtColor(bgr, hsv, COLOR_BGR2HSV);
Mat1b mask1, mask2;
inRange(hsv, Scalar(0, 0, 0, 0), Scalar(180, 255, 30, 0), mask1);
inRange(hsv, Scalar(0, 0, 0, 0), Scalar(180, 255, 40, 0), mask2);
Mat1b mask = mask1 | mask2;
imshow("Mask", mask);
waitKey();
return 0;
}
all the shapes are rounded with color black. I would like for my program to tell me how many of connected black objects are there. Also the writing under the shapes is also black. So It shows me this as well, that's okay, cause this is a test photo anyway.
How can I modify my program to detect how many connected black objects are in the photo? (In this photo, the output should be "60" as there are 8 objects and 49 letters + 3 letters are 'i' so we have to count the dots).
EDIT:
I want the program to count black objects. I already get all black objects out like this:
Upvotes: 1
Views: 1316
Reputation: 3115
If you want to count the number of objects just do the following:
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); // canny_output is the binary image
This will give you all the contours in the binary image (contours.size()). If you want only specific contours you can filter with contour area.
Hope it helps!
Upvotes: 1