【发布时间】:2020-05-20 22:47:24
【问题描述】:
我想擦除以下图像的黑色背景,这意味着将黑色像素设置为透明,就像在 .png 文件中一样。
这张图片是用以下代码完成的:
plt.imshow(terrain,cmap='magma')
其中terrain 是一个(n, n) 维NumPy 数组,terrain[i,j] 在range(0,9) 中。
【问题讨论】:
标签: python image numpy matplotlib
我想擦除以下图像的黑色背景,这意味着将黑色像素设置为透明,就像在 .png 文件中一样。
这张图片是用以下代码完成的:
plt.imshow(terrain,cmap='magma')
其中terrain 是一个(n, n) 维NumPy 数组,terrain[i,j] 在range(0,9) 中。
【问题讨论】:
标签: python image numpy matplotlib
您可以从您的整数数组和您使用的颜色图创建一个 RGBA 图像,然后将 alpha 通道设置为 0 以获得您想要具有透明度的值。然后,您可以在 Matplotlib 的savefig 命令中设置transparent=True。
这是一个代码sn-p:
import numpy as np
from matplotlib import pyplot as plt
# Mockup data
terrain = np.zeros((200, 200), np.uint8)
terrain[20:180, 20:180] = np.random.randint(0, 10, (160, 160))
# Generate RGBA image from colormapped grayscale data
cmap = plt.get_cmap('magma')
rgba_img = (cmap(terrain / np.max(terrain)) * 255).astype(np.uint8)
# Set alpha channel to 0 for all 0 values in terrain
rgba_img[:, :, 3] = (terrain > 0) * 255
# Output with transparency
plt.figure(0, figsize=(5, 5))
plt.imshow(rgba_img)
plt.axis('off')
plt.tight_layout()
plt.savefig('output.png', transparent=True)
然后输出如下所示:
希望有帮助!
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.8.1
Matplotlib: 3.2.0rc1
NumPy: 1.18.1
----------------------------------------
【讨论】:
经过检查,我注意到您图像中的黑色像素并非完全黑色。无论如何你可以试试这个:
from matplotlib import pyplot as plt
import numpy as np
import cv2
img = cv2.imread('test.png')
img_alpha = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
img_alpha[np.where((img==[3,0,0]).all(axis=2))] = [3,0,0,0]
plt.imshow(img_alpha,cmap='magma')
【讨论】:
terrain数组吗?
test.png 图像,在我的问题中,我在一个整数数组中有图像信息,该数组可以在range(9) 中具有值。这可能需要将凹凸不平的数组保存为图像,然后读取它。