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

时间:2021-07-31 17:47:16

标签: python opencv neural-network image-segmentation

我有一张肺的图像和该图片的预测掩码。它们看起来像这样: enter image description here

我想获得一张图像,在那里我可以看到某种颜色的预测区域。到目前为止,我设法做的是绘制轮廓。它看起来像这样(黄色): enter image description here

我的代码:

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()

有人可以解释一下我应该怎么做才能得到这样的结果: enter image description here

1 个答案:

答案 0 :(得分:3)

您可以使用蒙版在 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]