无法将 tiff PIL 图像转换为字节数组

问题描述 投票:0回答:1

我有一个 .tiff 图像加载到 PIL 图像中,我正在尝试获取它的字节数组。

这就是我正在做的事情:

from PIL import Image
import io

def image_to_byte_array(image: Image) -> bytes:
    imgByteArr = io.BytesIO()
    image.save(imgByteArr, format=image.format)
    imgByteArr = imgByteArr.getvalue()
    return imgByteArr

im = Image.open(r"ImagePath")
im_bytes = image_to_byte_array(im)

当我尝试将图像保存到 imgByteArr 时,问题就出现了。

一些 .tiff 图像抛出字典中的错误设置,此外我还得到 _TIFFVSetField: : 忽略标签“OldSubfileType”(libtiff 不支持)

这些情况有解决办法吗?

这是一个样本图片

python python-3.x python-imaging-library tiff
1个回答
0
投票

我现在很着急,但图像中有些东西(我猜是标签或压缩或某些属性)阻止您写入图像。

您可以像这样更简单地看到生成的错误:

from PIL import Image

im = Image.open(...path...)
im.save('anything.tif')

摆脱所有扩展属性和元数据的一种方法是将图像转换为 Numpy 数组,然后从那里转换回 PIL 图像。通过 Numpy 的这个“往返”不能传播任何属性,只能传播像素,因此它可以工作:

import numpy as np
from PIL import Image

im = Image.open(...path...)

# Round-trip through Numpy array to strip attributes and metadata
im = Image.fromarray(np.array(im))

im.save('anything.tif')    # works

当我有时间时我会进一步调查,但这可能作为临时方法。

© www.soinside.com 2019 - 2024. All rights reserved.