【问题标题】:Python - Getting TypeError when trying to save numpy array using Image.fromarray of PILPython - 尝试使用 PIL 的 Image.fromarray 保存 numpy 数组时出现 TypeError
【发布时间】:2021-07-11 05:19:33
【问题描述】:

我一直在尝试使用 PIL 在 numpy 数组的帮助下加载和存储图像。
我正在尝试加载尺寸为 192x192 的图像,将其填充为 256x256 ,然后将其存储回来。
这是我要运行的脚本:

from PIL import Image
from numpy import asarray
import numpy as np

#function to pad to 256x256
def pad_2d(data, r, c):
    res = np.zeros((r,c))
    m, n = data.shape
    
    res[(r-m)//2:(r-m)//2+m , (c-n)//2:(c-n)//2+n] = data
    return res

#function to remove padding
def crop_2d(data, r, c):
    m, n = data.shape
    
    return data[(m-r)//2:(m-r)//2+r , (n-c)//2:(n-c)//2+c]

file = "img1.png"

#image is successfully loaded in the form of numpy array and normalized 

data = asarray(Image.open(file)) # the data loaded, is of the shape (192,192,4)
data = (255.0 / data.max() * (data - data.min())).astype(np.uint8)

# dummy numpy array to store the 256x256 variant of 192x192 image by padding zeros
t = np.zeros((256,256,4))
for i in range(4):
    t[:,:,i] = pad_2d(data[:,:,i],256,256)
    
print(data.shape, t.shape) # prints : (192, 192, 4) (256, 256, 4)

img = Image.fromarray(t) # error occurs in this line
img.save('img2.png')


错误:
TypeError: Cannot handle this data type: (1, 1, 4), <f8


我已经交叉检查了 pad_2dcrop_2d 函数。它们都按预期工作。如果我尝试改为执行img = Image.fromarray(data),那么它可以通过保存与预期相同的图像来正常运行。


任何帮助将不胜感激。感谢阅读。

【问题讨论】:

    标签: python numpy python-imaging-library typeerror


    【解决方案1】:

    您无意中创建了一个浮点数组。改成这样:

    t = np.zeros((256,256,4), dtype=np.uint8)
    

    【讨论】:

    • 谢谢,它成功了。我原以为这与尺寸有关。
    猜你喜欢
    • 2018-02-08
    • 1970-01-01
    • 2020-12-14
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2022-10-21
    相关资源
    最近更新 更多