我想,最简单的方法是将基于调色板的数组转换为一些 RGBA 图像,将所有 nan 值的 alpha 通道设置为 0。然后,您可以简单地使用Image.paste 将此图像粘贴到背景图像上。
我设置了一个小示例,不知道您如何存储数据。因此,您可能需要调整该部分以适应您现有的实现。
import numpy as np
from PIL import Image
# Background image
bg = Image.open('path/to/your/image.png')
w, h = bg.size
# 2D array with values 0 - 3, and containing NaN values
a = np.random.randint(0, 4, (h, w)).astype(float)
b = (np.random.rand(h * w) < 0.90).reshape((h, w))
a[b] = np.nan
# Color palette for values 0 - 3
cp = np.array([[255, 0, 0], [0, 255, 0], [0, 0, 255], [128, 128, 128]])
# Replace palette with actual RGB values, set alpha = 0 for NaN values
img = np.zeros((h, w, 4), np.uint8)
for i in np.arange(cp.shape[0]):
img[a == i, :] = np.concatenate([cp[i, :], np.array([255])])
# Paste generated "foreground" image onto background image
img = Image.fromarray(img.astype(np.uint8))
bg.paste(img, mask=img)
bg.save('output.png')
中间图像看起来像这样(设置了四种不同的颜色,所有nan 值都被设为透明):
最终图像(可以看到背景图像,之前的nan值位于数组中):
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.9.1
PyCharm: 2021.1.1
NumPy: 1.20.2
Pillow: 8.2.0
----------------------------------------