numpy Python -将二进制掩码转换为多边形

7kqas0il  于 12个月前  发布在  Python
关注(0)|答案(4)|浏览(114)

给定一个简单的二进制掩码(例如,矩形的边界)。

如何使用多边形来获得x-y坐标?
这就是我到目前为止所尝试的:

coords = np.transpose(np.nonzero(mask))

但是,这种方法会生成填充对象,而不是所需的边界。

plt.plot(coords[:, 1], coords[:,0])

基本上,我想一个列表的x-y坐标的白色像素使用此列表来重新绘制矩形(未填充)。

mzillmmw

mzillmmw1#

cv2.findContours适用于复杂形状和多个对象。Polygons列表包含coords列表,每个列表看起来像这样[x1,y1,x2,y2,x3,y3,...]。

contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
polygons = []

for obj in contours:
    coords = []
        
    for point in obj:
        coords.append(int(point[0][0]))
        coords.append(int(point[0][1]))

    polygons.append(coords)
apeeds0o

apeeds0o2#

可以使用np.column_stack() + np.where()。其思想是确定二进制图像中的白色像素,然后按相应的(x, y)顺序排序

coords = np.column_stack(np.where(image > 0))

另一种方法是使用OpenCV的cv2.boundingRect()查找边界矩形的坐标。这将给予宽度、高度和左上角的(x,y)坐标。这里有一个例子,找到坐标,然后绘制多边形到一个空白的面具

import cv2
import numpy as np

image = cv2.imread('1.png', 0)
x,y,w,h = cv2.boundingRect(image)
mask = np.ones(image.shape, dtype=np.uint8) * 255
mask = cv2.merge([mask,mask,mask])
cv2.rectangle(mask, (x, y), (x + w, y + h), (36,255,12), 2)

cv2.imshow('mask', mask)
cv2.waitKey()
plicqrtu

plicqrtu3#

你可以把正方形当作一个对象,并使用skimage.measure.regionprops函数访问它的属性。
我强烈建议您查看文档,因为它在许多情况下都是非常有用的功能:
https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.regionprops
此外,还有skimage.measure.regionprops_table,它给了你一个字典来转换到Pandas框架。
我的解决方案如下:

from skimage.io import imread
from skimage.measure import regionprops_table
from pandas import DataFrame

import numpy as np
import matplotlib.pyplot as plt

rectangle = imread('rectangle_img.png')    
props_rect = DataFrame(regionprops_table(rectangle, properties=['coords']))

new_img = np.zeros((rectangle.shape[0], rectangle.shape[1]))

for point in props_rect['coords'][0]:

    new_img[point[0], point[1]] = 1

plt.imshow(new_img)
s1ag04yj

s1ag04yj4#

contours, _ = cv2.findContours(binary_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
polygons = [np.array(polygon).squeeze() for polygon in contours]

polygons是一个listarrays的形状为N, 2,其中N对应于点数,2对应于xy坐标

相关问题