使用 Pillow 在 Python 中将数组转换为图像(tif)

Pro*_*eus 2 python arrays python-imaging-library pillow

我正在尝试将 anarray转换为图像(tif)进行压缩(它将在另一端撤消)。然而,我在第一个障碍上摔倒了......

我有以下几点:

pillow_image = Image.fromarray(image_data)
Run Code Online (Sandbox Code Playgroud)

这给了我这个错误:

  File "/Users/workspace/test-app/env/lib/python2.7/site-packages/PIL/Image.py",
Run Code Online (Sandbox Code Playgroud)

第 2155 行,在 fromarray arr = obj 中。array_interface AttributeError: 'tuple' 对象没有属性 ' array_interface '

我在这里做错了什么?

unu*_*tbu 5

image_data是 4 个 numpy 数组的元组,每个(可能)形状为 (H, W)。您需要image_data是单个形状数组 (H, W, 4)。因此,使用np.dstack组合通道。

至少有一个数组具有 dtype int32。但是要将其用作 8 位颜色通道,数组需要是 dtype uint8(因此最大值为 255)。您可以在阵列D型转换uint8使用astype。希望您的数据不包含大于 255 的值。如果是,astype('uint8')将只保留最低有效位(即返回数字模 256)。

image_data = np.dstack(image_data).astype('uint8')
pillow_image = Image.fromarray(image_data)
Run Code Online (Sandbox Code Playgroud)