Python - 尝试使用 PIL 的 Image.fromarray 保存 numpy 数组时出现 TypeError
Python - Getting TypeError when trying to save numpy array using Image.fromarray of PIL
我一直在尝试使用 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_2d
和 crop_2d
函数。他们都按预期工作。如果我尝试改为执行 img = Image.fromarray(data)
,那么通过按预期保存相同的图像,它 运行 没问题。
如有任何帮助,我们将不胜感激。感谢阅读。
您无意中创建了一个浮点数组。更改为:
t = np.zeros((256,256,4), dtype=np.uint8)
我一直在尝试使用 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_2d
和 crop_2d
函数。他们都按预期工作。如果我尝试改为执行 img = Image.fromarray(data)
,那么通过按预期保存相同的图像,它 运行 没问题。
如有任何帮助,我们将不胜感激。感谢阅读。
您无意中创建了一个浮点数组。更改为:
t = np.zeros((256,256,4), dtype=np.uint8)