如何从两个Numpy数组中为PNG创建字节数组

6qfn3psc  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(144)

我有两个Numpy数组(一个有位置数据,另一个有颜色数据),我试图将它们转换为可以表示为PNG的字节数组。位置阵列具有(N,2)的形状,颜色阵列具有(N,3)的形状,其中N=N。位置阵列中的2是X、Y数据,颜色阵列中的3是R、G、B数据。我不熟悉PNG文件结构的工作原理,但我基本上想让字节数组存储我的像素艺术,但具有透明的背景。我怎么能做到这一点?

cczfrluj

cczfrluj1#

你不会说最终图像的大小是什么,但是如果它的尺寸是(nx, ny),你可以用NumPy和PIL来做到这一点:

from PIL import Image
import numpy as np

# Test: set 2 pixels in a 4x3 image.
N = 2
nx, ny = 4, 3
# Specify the colours of pixels at these (x,y) coordinates
pos = np.array([[0,0], [1,1]])
col = np.array([[0,255,255], [255,0,0]])

# Set the alpha channel of the coloured pixels to 255: opaque
cola = np.ones((N,4)) * 255
cola[:,:3] = col
# The image RGBA array: initially set all pixels to transparent (alpha=0)
img = np.zeros((nx, ny, 4), dtype=np.uint8)
# Set the pixels' colours.
img[pos[:,0],pos[:,1]] = cola

# Turn the array into a PIL Image and save it.
im = Image.fromarray(img)
im.save("image.png")

相关问题