如何将语义段生成的二维值数组另存为图像?

问题描述 投票:0回答:1

[当图像作为语义分割模型的输入提供时,其输出是2D值数组。该数组中的每个值代表模型认为存在于原始图像中该位置的对象。数组看起来像这样:

print(image_mask)

array([[2, 2, 2, ..., 7, 7, 7],
       [2, 2, 2, ..., 7, 7, 7],
       [2, 2, 2, ..., 7, 7, 7],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]])

[当使用matplotlib将其绘制为图像时,它会添加假色并生成图像:

plt.imshow(image_mask)

enter image description here

将该数组绘制在图像的顶部会产生类似effect的蒙版:

plt.subplot(1,2,1)
plt.imshow(image, 'gray', interpolation='none')
plt.subplot(1,2,2)
plt.imshow(image, 'gray', interpolation='none')
plt.imshow(image_mask, 'jet', interpolation='none', alpha=0.7)
plt.show()

enter image description here

现在,我的目标是使用模型创建的蒙版在图像中提取人物。最初,我以为image_mask是一个3通道RGB图像,并试图使图像中的黄色变为白色,背景变为黑色,如下所示:

image_mask[np.where((image_mask==[253,231,36]).all())] = [255,255,255] # MAKE YELLOW WHITE
image_mask[np.where((image_mask==[68,1,84]).all())] = [0,0,0] # MAKE BACKGROUND BLACK
result = cv2.bitwise_and(image,image,mask = image_mask) # DO BITWISE AND WITH THE ORIGINAL TO GET THE PEOPLE

但是我很快意识到这不可能,因为image_mask不是图像。我现在该怎么办?有没有办法将此数组转换为图像?还是在这种情况下cv2提供了一些方法来帮助您?

python matplotlib mask cv2
1个回答
0
投票

知道了!

我将矩阵乘法与np.expand_dims一起使用:

image_mask_copy = image_mask.copy()
np.place(image_mask_copy,image_mask_copy!=15,[0]) # REMOVE ALL EXCEPT PEOPLE, == 0
np.place(image_mask_copy,image_mask_copy==15,[255]) # MAKE PEOPLE == 255
plt.imshow(image_mask_copy)

enter image description here


new_image_mask = np.expand_dims(image_mask_copy,-1)*np.ones((1,1,3))
plt.imshow(new_image_mask)

enter image description here

现在是图像。

© www.soinside.com 2019 - 2024. All rights reserved.