In this post, I am demonstrating how OpenCV contour and Moments work, below code will do, load image, convert to gray, smooth image , threshold image, find contour and find moment and centroid for the contour. Finally draw contour centre on source image and display the result.
3. Blur operation to remove the noise
4. Threshold the image to process contour
6. Get moment and Centroid of the contour
Step 1
1. Load Image in color mode
Mat src = imread("shapes.jpg", 1);
Step 2
2. Convert to grayscale3. Blur operation to remove the noise
4. Threshold the image to process contour
Mat gray, thr;
cvtColor(src, gray, COLOR_BGR2GRAY);
blur(gray, gray, Size(10, 10), Point(-1, -1), BORDER_DEFAULT);
threshold(gray, thr, 50, 255, THRESH_BINARY);
Step 3
5. FindContours to get all contour6. Get moment and Centroid of the contour
vector< vector > contours; // Vector for storing contour
vector hierarchy;
findContours(thr, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE); // Find the contours in the image
// get the moments
vector mu(contours.size());
for (int i = 0; i < contours.size(); i++) {
mu[i] = moments(contours[i], false);
}
// get the centroid
vector mc(contours.size());
for (int i = 0; i < contours.size(); i++) {
mc[i] = Point2f(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00);
}
// draw centroid
for (int i = 0; i < contours.size(); i++) {
circle(src, mc[i], 5, Scalar(255, 255, 255), -1, 8,0); // draw centroid circle
line(src, mc[i], Point(mc[i].x, mc[i].y - 100), Scalar(255, 255, 255), 1,8);
String txt = format("Contour %d", i);
putText(src, txt, Point(mc[i].x - 50, mc[i].y - 110), FONT_HERSHEY_SIMPLEX, 1, CV_RGB(255, 0, 0), 2);
}
Full C++ Code
Mat src = imread("shapes.jpg", 1);
Mat gray, thr;
cvtColor(src, gray, COLOR_BGR2GRAY);
blur(gray, gray, Size(10, 10), Point(-1, -1), BORDER_DEFAULT);
threshold(gray, thr, 50, 255, THRESH_BINARY);
vector< vector > contours; // Vector for storing contour
vector hierarchy;
findContours(thr, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE); // Find the contours in the image
// get the moments
vector mu(contours.size());
for (int i = 0; i < contours.size(); i++) {
mu[i] = moments(contours[i], false);
}
// get the centroid
vector mc(contours.size());
for (int i = 0; i < contours.size(); i++) {
mc[i] = Point2f(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00);
}
// draw centroid
for (int i = 0; i < contours.size(); i++) {
circle(src, mc[i], 5, Scalar(255, 255, 255), -1, 8, 0); // draw centroid circle
line(src, mc[i], Point(mc[i].x, mc[i].y - 100), Scalar(255, 255, 255), 1, 8);
String txt = format("Contour %d", i);
putText(src, txt, Point(mc[i].x - 50, mc[i].y - 110), FONT_HERSHEY_SIMPLEX, 1, CV_RGB(255, 0, 0), 2);
}
imshow("thr", thr);
imshow("src", src);
imwrite("contour.jpg", src);
imwrite("contour_thr.jpg", thr);
waitKey();
No comments:
Post a Comment