Is it possible to write each found closed contour into a separate image file?
I have a code like this:
//Finding contours
vector<vector<Point> > img_contours;
vector<Vec4i> hierarchy;
findContours( img0, img_contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0,0) );
//Drawing contours
Mat contours_closed = Mat::zeros( img0.size(), CV_8UC1 );
RNG rng(12345);
int counter_closed_contours = 0;
for (int i = 0; i < img_contours.size(); i++) {
double area = contourArea( img_contours[i] );
if (area > 2610 && hierarchy[i][2] < 0){
counter_closed_contours++;
//HERE I DON'T KNOW HOW TO CODE AND WHERE TO PUT IMWRITE
imwrite("Contour_" + std::to_string(counter_closed_contours) + ".jpg", img_contours[i] );
Scalar color = Scalar( rng.uniform(255, 255), rng.uniform(255, 255),rng.uniform(255, 255));
drawContours( contours_closed, img_contours, i, color, CV_FILLED );
}
};
Code itself works fine, it finds closed contours and draws them. But since I want each contour in a separate file I don't know where to use imwrite and whether it's possible to get contour by contour inside a loop since it looks like drawContours returns an image of contours in one shot
Inside the for
loop you have to perform 2 important operations:
cv::Mat
to cv::Scalar(0)
. cv::drawContours()
. This can be done using the following code:
# Create a single channel image with black color.
cv::Mat contourMat = cv::Mat(img0.size(), CV_8UC1, cv::Scalar(0));
# Iterate over all the contours.
for (int i=0; i<contours.size(); i++) {
# Draw the given contour, on the black canvas.
drawContours(contourMat, img_contours, i, cv::Scalar(255), CV_FILLED );
cv::imwrite("Contour_" + std::to_string(counter_closed_contours) + ".jpg", contourMat);
# Reset the image again to black.
contourMat.setTo(cv::Scalar(0));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.