gpt4 book ai didi

python - PIL 图像到阵列和返回

转载 作者:行者123 更新时间:2023-12-01 02:18:26 24 4
gpt4 key购买 nike

编辑:抱歉,代码的第一个版本是废话,我试图删除无用的信息并犯了一个错误。问题保持不变,但现在是我实际使用的代码

我认为我的问题可能非常基本,但我找不到解决方案。我基本上只是想使用 PIL 并将图像转换为数组并向后转换,然后保存图像。看起来应该是一样的,对吧?就我而言,新图像只是胡言乱语,它似乎有一些结构,但它不是应有的飞机图片:

def array_image_save(array, image_path ='plane_2.bmp'):
image = Image.fromarray(array, 'RGB')
image.save(image_path)
print("Saved image: {}".format(image_path))

im = Image.open('plane.bmp').convert('L')
w,h = im.size
array_image_save(np.array(list(im.getdata())).reshape((w,h)))

最佳答案

不完全确定您要实现的目标,但如果您只想将图像转换为 numpy 数组并返回,则可以使用以下方法:

from PIL import Image
import numpy as np

def array_image_save(array, image_path ='plane_2.bmp'):
image = Image.fromarray(array)
image.save(image_path)
print("Saved image: {}".format(image_path))

im = Image.open('plane.bmp')
array_image_save(np.array(im))

您可以将 PIL 图像传递给 np.array,它会负责正确的整形。获得扭曲数据的原因是因为您将 pil 图像转换为灰度 (.convert('L')),但随后尝试将其保存为 RGB。

关于python - PIL 图像到阵列和返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48154011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com