如何在图像分割任务中填充蒙版内的分割区域?

How to fill segmented area within a mask in image segmentation task?

我有一张肺部图像和该图片的预测遮罩。它们看起来像这样:

我想要一张图像,其中我将看到某种颜色的预测区域。到目前为止我设法做的是绘制轮廓。看起来像这样(黄色):

我的代码:

lung = Image.fromarray(images_medseg[0])
if lung.mode != 'RGB':
lung = lung.convert('RGB')
lung.save("main.jpeg")

mask = Image.fromarray((masks_medseg[0] * 255).astype(np.uint8))
if mask.mode != 'RGB':
mask = mask.convert('RGB')
mask.save("segmented.jpeg")

seg  = cv2.imread('segmented.jpeg',cv2.IMREAD_GRAYSCALE)
main = cv2.imread('main.jpeg',cv2.IMREAD_GRAYSCALE)
main = cv2.cvtColor(main,cv2.COLOR_GRAY2BGR)

RGBforLabel = { 1:(0,0,255), 2:(0,255,255) }

# Find external contours
contours, _ = cv2.findContours(seg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# Iterate over all contours
for i,c in enumerate(contours):
# Find mean colour inside this contour by doing a masked mean
mask = np.zeros(seg.shape, np.uint8)
cv2.drawContours(mask,[c],-1,255, -1)
cv2.imwrite(f"mask-{i}.png", mask)
mean,_,_,_ = cv2.mean(seg, mask=mask)
# DEBUG: print(f"i: {i}, mean: {mean}")

# Get appropriate colour for this label
label = 2 if mean > 1.0 else 1
colour = RGBforLabel.get(label)
# DEBUG: print(f"Colour: {colour}")

# Outline contour in that colour on main image, line thickness=1
cv2.drawContours(main,[c],-1,colour,1)



# Save result
cv2.imwrite('result.png',main) 

res = mpimg.imread('/content/result.png')
imgplot = plt.imshow(res)
plt.show()

有人可以解释一下我应该怎么做才能得到这样的东西:

您可以在 Python/OpenCV 中使用 Numpy 使用蒙版为图像着色,其中蒙版为白色。如果我们假设您的掩码是二进制的(0 和 255),那么

result = image.copy()
result[mask==255] = [0,255,255]

或者,如果这不起作用并且您的掩码是 3 个通道但二进制(0 和 255),那么

result = image.copy()
result[np.where((mask==[255,255,255]).all(axis=2))] = [0,255,255]