Numpy 生成 x,y 坐标,导致分割掩码被对角线分割

Numpy where generating x,y coordinates that cause segmentation mask to be diagonally split

下面是一张图片:

这是此图像中 class 的分割蒙版:

注意上面的分割掩码是"porous"。我的目标是使用 Numpy 在其边界框内生成一个完全填充的分割掩码。不幸的是,我目前尝试这样做的结果是分割蒙版是条纹的、有渐变的、透明的,并且在边界框的对角线上被分割(下图)。我不知道为什么会这样。

当前(不正确)结果:

代码(参见比较 1 和 2):

# define row in pandas df
row = annotations_df.iloc[2]

# image width, height
img_w = annotations_df.iloc[0].width
img_h = annotations_df.iloc[0].height

# bounding box matrix 
bbox = np.zeros((img_h, img_w))

### compare 1 ---> this is the original mask
x_coords, y_coords = ast.literal_eval(row.x_coords), ast.literal_eval(row.y_coords)

### compare 2 ---> this should produce a filled mask (and does not work as expected)
bbox[min(y_coords):max(y_coords)+1,min(x_coords):max(x_coords)+1] = 1
y_coords, x_coords = np.where(bbox == 1)

# set fig, axes, style
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])

# read image, plot image
img = plt.imread(first_row.path.values[0])
plt.imshow(img)

# convert coordinates to form of (x,y)
pts = np.array(list(zip(x_coords, y_coords)))

# get min/max of coordinates
xmin = min(x_coords)
xmax = max(x_coords)
ymin = min(y_coords)
ymax = max(y_coords)
width = xmax - xmin
height = ymax - ymin

# plot bounding box
rect = patches.Rectangle((xmin,ymin), width, height, edgecolor = 'c', facecolor = 'none')
ax.add_patch(rect)

# plot mask
poly = patches.Polygon(pts)
ax.add_patch(poly)

正确的输出是一个完全填充的边界框。

您没有问题。它工作正常:

poly = patches.Polygon(pts)

一个可爱但相当复杂的多边形... 您希望它绘制边界,但您传递了该区域中所有点的所有坐标。 您可能想尝试:

poly = patches.Polygon([[xmin,ymin],[xmin,ymax],[xmax,ymax],[xmax,ymin]])

ps:我假设您使用的是 matplotlib Polygon