如何以编程方式将图像处理为黑白并分离出多边形

How to programatically process the image to black and white and separate out the polygon

我有一个表示多边形的图像。

我想在matlab中处理生成下图

基本上我要求将多边形与图像的其余部分分开。这个问题得到了启发 .

我认为函数 contourc 会得到 ploygon:

C = contourc(img, [1 1]); % img is 2-D double in range [0 1]

输出C的格式有点棘手。但是对于一个级别的轮廓,它应该很容易。您可以阅读 contourc 的文档来构建多边形。

我们只对红色像素感兴趣,我们可以使用第一个通道(红色)来提取每个缩放像素的坐标质心。由于相同坐标之间可能存在细微差异,我们可以使用 uniquetol 函数的第三个输出将绝对坐标转换为相对坐标,然后使用 accumarray 将坐标转换为二进制图像。

[a,m]=imread('KfXkR.png');                             %read the indexed image
rgb = ind2rgb(a,m);                                    %convert it to rgb
region = rgb(:,:,1)>.5;                                %extract red cannel convert to binary to contrast red pixels
cen = regionprops(region,'Centroid');                  %find absolute coordinates of centeroid of each pixel
colrow = reshape([cen.Centroid],2,[]);                 %reformat/reshape
[~,~,col] = uniquetol(colrow(1,:),0.1,'DataScale',1);  %convert absolute coordinated to relative coordinates correcting possible slight variations
[~,~,row] = uniquetol(colrow(2,:),0.1,'DataScale',1);
result = accumarray([row col],1);                      %make the binary image from coordinates of pixels
imwrite(result,'result.png')

缩放结果:

未缩放: