【问题标题】:why does saving an image to an array and reloading it doesn't show the same image?为什么将图像保存到数组并重新加载它不会显示相同的图像?
【发布时间】:2021-09-22 13:44:54
【问题描述】:

我想将图像(图像:img)保存到数组中,将数组保存为 .csv 格式,然后将 .csv 文件加载到不同的数组中并显示图像。 但是最后的图像不是我之前保存的图像。相反,我只看到条纹和正方形...the picture at the end

代码:

import numpy as np
from PIL import Image

#saving the image to an array
a = np.array(Image.open("C:\\Users\\Patrick\\Desktop\\1.png").convert("L"))

#showing the image from array
image = Image.fromarray(a, "L")
image.show()

#saving the array to .csv file
array_save = np.savetxt("C:\\Users\\Patrick\\Desktop\\array_save.csv", a, delimiter=",")
array = np.loadtxt("C:\\Users\\Patrick\\Desktop\\array_save.csv", delimiter=",")
array = array.astype(int)

#showing the image from array put of the .csv file
image = Image.fromarray(array, "L")
image.show()

我真的不知道为什么我看不到图像。数组应该是相同的,当我将它们打印出来时,它们对我来说看起来是一样的。

【问题讨论】:

  • 请格式化代码以使其可读,在代码顶部添加```python,在代码底部添加```(顺便说一句,这些是反引号,而不是引号)
  • 打开 PIL 图像似乎很疯狂,将其变为 Numpy 数组只是为了将其改回 PIL 图像。我会用image = Image.open().convert() 替换前两行然后a = np.array(image)

标签: python arrays image csv


【解决方案1】:

创建的 a 数组的类型为 uint8,但是当您从 CSV 文件重新创建数组时,您指定的是 int。将此更改为np.uint8,它应该可以工作:

import numpy as np
from PIL import Image

#saving the image to an array
a = np.array(Image.open("1.png").convert("L"))

print(a.dtype)   # show the array type
#showing the image from array
image = Image.fromarray(a, "L")
image.show()

#saving the array to .csv file
array_save = np.savetxt("array_save.csv", a, delimiter=",")
array = np.loadtxt("array_save.csv", delimiter=",")
array = array.astype(np.uint8)

#showing the image from array put of the .csv file
image = Image.fromarray(array, "L")
image.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多