我有一个简单,人为的例子,使用带有OpenCV C API的cvFindContours在二进制图像上查找连接的组件。 (这是用C编写的更大软件的一部分,因此使用C ++ API不是一种选择。)
示例输入图像由黑色背景上的两个填充的白色方块组成,不重叠。我希望得到两个轮廓,代表构成每个方格周长的连通分量。相反,我得到四个组件。为什么?详情如下。
首先我将输入图像设置为'self',这是一个CV_32FC1图像,背景像素为0.0,白色像素(两个正方形)的值为1.0:
cvThreshold(self, self, 0.8, 1.0, CV_THRESH_BINARY);
然后我使用cvScale将输入图像复制到相同大小的CV_32SC1图像:
CvMat * temp = cvCreateMat(height, width, CV_32SC1);
cvConvertScale(self, temp, 1, 0);
然后我执行cvFindContours以获取连接的组件:
CvSeq * components = 0;
CvMemStorage * mem = cvCreateMemStorage(0);
cvFindContours(temp, mem, &components, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));
然后我执行以下操作输出构成轮廓的点并将它们绘制到窗口。
for(; components != 0; components = components->h_next)
{
printf("===============NEW COMPONENT!============\n");
if (components->v_next) printf("This has a child.\n");
CvPoint * pt_array = (CvPoint *)malloc(components->total*sizeof(CvPoint));
cvCvtSeqToArray(components, pt_array, CV_WHOLE_SEQ);
for (int i = 0; i < components->total; i++)
{
printf("Point %i: %i, %i\n", i, pt_array[i].x, pt_array[i].y);
}
free(pt_array);
outer_color = CV_RGB(rand()%255, rand()%255, rand()%255);
cvDrawContours(dst, components, outer_color, inner_color, -3, 1, 8, cvPoint(0,0));
}
我希望这能产生两个轮廓,代表我二进制图像中两个白色方块的周长。相反,我得到了四个顶级轮廓,它们大致相互重叠。是什么给了什么?
四个等高线中的点如下:
===============NEW COMPONENT!============
Point 0: 200, 150
Point 1: 200, 199
Point 2: 199, 200
Point 3: 150, 200
Point 4: 149, 199
Point 5: 149, 150
Point 6: 150, 149
Point 7: 199, 149
===============NEW COMPONENT!============
Point 0: 150, 150
Point 1: 150, 199
Point 2: 199, 199
Point 3: 199, 150
===============NEW COMPONENT!============
Point 0: 50, 10
Point 1: 50, 49
Point 2: 49, 50
Point 3: 10, 50
Point 4: 9, 49
Point 5: 9, 10
Point 6: 10, 9
Point 7: 49, 9
===============NEW COMPONENT!============
Point 0: 10, 10
Point 1: 10, 49
Point 2: 49, 49
Point 3: 49, 10