i have a grayscale which has only binary color (on left of above image), run Canny on it, the right part of above image is result. The result contours can not end in closure, the contours just wrap the border like the right line. So points like (60,50)(70,60) are out of polygon from contours by using cv::pointPolygonTest.
simple test code as following:
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
using namespace cv;
using namespace std;
#define AREA_COLOR_IN_GRAYSCALE 100
Mat ReadGrayscale(const char* filename)
{
Mat src = imread(filename);
if( src.empty() )
{
printf("Could not open or find the image!\n");
}
return src;
}
void GetContoursAndGenPolygon(const char *filename)
{
int32_t threshH = AREA_COLOR_IN_GRAYSCALE - 1;
int32_t threshL = threshH >> 1;
Mat grayscale = ReadGrayscale(filename);
Mat edgeMat;
Canny(grayscale, edgeMat, threshL, threshH);
cv::imwrite("edge.ppm", edgeMat);
vector<vector<Point> > contours;
findContours(edgeMat, contours, CV_RETR_EXTERNAL, CHAIN_APPROX_SIMPLE );
for( size_t i = 0; i< contours.size(); i++ )
{
printf("contour[%zd] has %zd points\n", i, contours[i].size());
for (const auto& p : contours[i])
{
printf("(%d,%d) ", p.x, p.y);
}
printf("\n");
}
auto checkPolygon = [&](cv::Point2f p)
{
double d = cv::pointPolygonTest(contours[0], p, false);
printf("(%.0f,%.0f) is %s polygon, d %.2f\n", p.x, p.y, (d >= 0.0) ? "in" : "out of", d);
};
if (contours.size() >= 1)
{
checkPolygon(cv::Point2f(60,50));
checkPolygon(cv::Point2f(70,60));
}
}
int main( int argc, char** argv )
{
printf("opencv verison %d.%d\n", CV_MAJOR_VERSION, CV_MINOR_VERSION);
GetContoursAndGenPolygon("concave.ppm");
return 0;
}
the output
opencv verison 3.3
contour[0] has 29 points
(57,46) (55,48) (55,51) (56,52) (64,52) (65,53) (65,64) (66,65) (72,65) (72,54) (71,53) (67,53) (71,53) (72,54) (72,64) (71,65) (66,65) (65,64) (65,53) (64,52) (56,52) (55,51) (55,48) (57,46) (65,46) (66,47) (66,51) (66,47) (65,46)
(60,50) is out of polygon, d -1.00
(70,60) is out of polygon, d -1.00
My questions:
1. why contours are not closed around point (66,52)
2. how to avoid it, i want to get a correct polygon