C++ OpenCV 关闭一个形状并填充它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12929197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:46:11  来源:igfitidea点击:

OpenCV closing a shape and filling it

c++opencvshapefillcontour

提问by Og Namdik

I want to output a blue-filled hand but get the incorrect output. I've included the input picture, incorrect output picture and code below.

我想输出一个蓝色填充的手,但得到不正确的输出。我在下面包含了输入图片、不正确的输出图片和代码。

i think the code below does not fill the whole image because the image isn't closed yet at the right boundary.

我认为下面的代码没有填满整个图像,因为图像还没有在右边界关闭。

how do i close the shape and fill it with blue properly?

我如何关闭形状并正确填充蓝色?

close shape

闭合形状

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace cv;
using namespace std;

void drawStuff();
void showInputWindow();
void showCannyWindow();
void showContourWindow();

int thresh = 40;
int max_thresh = 120;
Mat img_rgb,img_gray,img_bw,canny_output,drawing;

int main(){
    img_rgb  = imread("qq.jpg");
    blur( img_rgb, img_rgb, Size(3,3) );
    cvtColor(img_rgb,img_gray,CV_RGB2GRAY);
    showInputWindow();

    drawStuff();
    cv::waitKey(0);
}

void drawStuff(){
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;

    Canny( img_gray, canny_output, thresh, thresh*2, 3 );
    cv::dilate(canny_output, canny_output, cv::Mat(), cv::Point(-1,-1));
    showCannyWindow();

    findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
    drawing = Mat::zeros( canny_output.size(), CV_8UC3 );

    vector<Point> approxShape;
    for(size_t i = 0; i < contours.size(); i++){
        approxPolyDP(contours[i], approxShape, arcLength(Mat(contours[i]), true)*0.04, true);
        drawContours(drawing, contours, i, Scalar(255, 0, 0), CV_FILLED);   // fill BLUE
    }

    showContourWindow();
}

void showInputWindow(){
    cv::namedWindow("InputImage");
    cv::imshow("InputImage",img_rgb);
}

void showCannyWindow(){
    cv::namedWindow("Canny");
    cv::imshow("Canny",canny_output);
}
void showContourWindow(){
    cv::namedWindow("Fill");
    cv::imshow("Fill",drawing);
}

回答by Marek

To solve your problem, you should detect only outer contours. By doing that you will get only one contour, and you can fill it with your color.

要解决您的问题,您应该只检测外部轮廓。这样你只会得到一个轮廓,你可以用你的颜色填充它。

findContours( canny_output, contours, hierarchy, Imgproc.RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );