在我回答您的实际问题之前,先谈谈您的评论,以及为什么您的问题可能会被否决。你的代码不是minimal, reproducible example,也不能按原样工作。
您缺少所有必要的导入:
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
你的方法参数之一是错误的:
def display_image(pixels, name=""): # <-- I assume, pixels should be array here.
if name:
plt.imsave(name, array)
plt.imshow(array)
plt.show() # <-- Without, there's no actual output.
im 是什么?最有可能的是,这是一些 PIL 图像。此外,您硬编码了一些值,但没有提供相应的图像。
im = Image.open('someImage.jpg') # <-- Need to load some image at all.
pixels = im.getdata()
pixelMap = im.load()
npImage = np.array(pixels).reshape(671, 450, 3) # <-- That only works for images with the specific size
display_image(npImage) ## great!
在最后一个测试用例中,您没有更新npImage:
pixels = list(pixels) ## pixels var originally imagecore class
for index in range(len(pixels)):
pixels[index] = (float(pixels[index][0]), float(pixels[index][1]), float(pixels[index][2]))
# <-- You updated pixels, but not npImage
display_image(npImage, "monaLisa.jpg")
只有在解决所有这些问题后,才会出现实际错误,您在问题中谈论的是!
现在,你的错误:
Traceback (most recent call last):
File "[...].py", line 18, in <module>
display_image(npImage, "image.jpg") ## error, must be floats.
[...]
ValueError: Image RGB array must be uint8 or floating point; found int32
您的npImage 是int32 类型,但plt.imsave 需要uint8(值0 ... 255)或float(值0.0 ... 1.0)用于写入。
所以,让我们强制执行uint8:
npImage = np.array(pixels, dtype=np.uint8).reshape(..., 3)
如上所述添加npImage的必要更新后
pixels = list(pixels) ## pixels var originally imagecore class
for index in range(len(pixels)):
pixels[index] = (float(pixels[index][0]), float(pixels[index][1]), float(pixels[index][2]))
npImage = np.array(pixels).reshape(..., 3) # <-- This line
display_image(npImage, "monaLisa.jpg") ## works but incorrect image
出现以下错误:
Traceback (most recent call last):
File "[...].py", line 25, in <module>
display_image(npImage, "monaLisa.jpg") ## works but incorrect image
[...]
ValueError: Floating point image RGB values must be in the 0..1 range.
您尚未将您的 float 值缩放到 0.0 ... 1.0。所以,我们只除以255:
npImage = np.array(pixels).reshape(..., 3) / 255
我无法重现您的“完全修改的图像”(由于可能缺少代码片段),但这很可能也是由于未缩放的 float 值,并且您可能看到了剪辑。 (图像几乎是白色的吗?)
希望有帮助!