您可以使用整数数组和使用的颜色图创建RGBA图像,然后将Alpha通道设置为0,以使其具有透明度。然后,您可以transparent=True
在Matplotlib的savefig
命令中进行设置。
这是一个代码片段:
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
----------------------------------------
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句