给定一个简单的二进制掩码(例如矩形的边界)。
如何使用多边形获取x-y坐标?
到目前为止,我尝试过以下方法:
coords = np.transpose(np.nonzero(mask))
然而,这种方法会生成一个填充的对象,而不是所期望的边界。
plt.plot(coords[:, 1], coords[:,0])
基本上,我需要一个白色像素的x-y坐标列表,使用这个列表重新绘制矩形(非填充)。
给定一个简单的二进制掩码(例如矩形的边界)。
如何使用多边形获取x-y坐标?
到目前为止,我尝试过以下方法:
coords = np.transpose(np.nonzero(mask))
plt.plot(coords[:, 1], coords[:,0])
基本上,我需要一个白色像素的x-y坐标列表,使用这个列表重新绘制矩形(非填充)。
使用cv2.findContours
既适用于复杂形状,也适用于多个对象。 Polygons
列表包含coords
列表,每个列表看起来像这样[x1,y1,x2,y2,x3,y3,...]。
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
polygons = []
for object in contours:
coords = []
for point in object:
coords.append(int(point[0][0]))
coords.append(int(point[0][1]))
polygons.append(coords)
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()
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)
contours, _ = cv2.findContours(binary_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
polygons = [np.array(polygon).squeeze() for polygon in contours]
polygons
是一个包含形状为 N, 2
的 arrays
的 list
,其中 N
对应于点的数量,2
对应于 x
和 y
坐标。