dimmg
dimmg

Reputation: 3815

openCV better way to draw contours

I've detected the hand based on ROI histograms using the code provided on the openCV website, and this is the result I've obtainedenter image description here

Based on this result, I want to draw the contour, but the resulting image it's not the one I need for my future processing. enter image description here

What I need to do in order to have a smoother contour? Thanks!

Upvotes: 1

Views: 534

Answers (1)

Miki
Miki

Reputation: 41765

Your image has too many "holes". Try with some morphology

This is C++ code, but you can easily port to Python. You may need to tweak the parameters a little.

#include <opencv2\opencv.hpp>
using namespace cv;

int main()
{
    Mat3b img = imread("path_to_image");
    Mat1b binary;
    cvtColor(img, binary, CV_BGR2GRAY);
    threshold(binary, binary, 1, 255, THRESH_BINARY);

    Mat1b morph;
    Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(11,11));
    morphologyEx(binary, morph, MORPH_CLOSE, kernel, Point(-1,-1), 3);

    vector<vector<Point>> contours;
    findContours(morph.clone(), contours, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);

    /// Draw contours
    Mat3b draw = img.clone();
    for (int i = 0; i < contours.size(); i++)
    {
        drawContours(draw, contours, i, Scalar(0,0,255), 2);
    }

    return 0;
}

If you close your image, you got better results, like this:

enter image description here

Probably you need, however, to get a better result from your former processing.

Upvotes: 1

Related Questions