【问题标题】:converting an Image into numpy array, then save into txt file, then again converting .txt in image将图像转换为 numpy 数组,然后保存到 txt 文件中,然后再次将 .txt 转换为图像
【发布时间】:2019-10-31 16:40:12
【问题描述】:

我有三个阶段: 1. 将 Image 转换为 numpy 数组 2. 将该数组保存在文本文件中 3. 通过读取该文本文件将数组转换为图像

我尝试了下面的代码,它将图像转换为数组并再次从文本文件中读取相同的数组

from PIL import Image
import numpy
im = Image.open("a.jpg") # img size (480,910,3)

np_im = numpy.array(im)

with open('test.txt', 'w') as outfile:
    for slice_2d in np_im:
        numpy.savetxt(outfile, slice_2d)

new_data = numpy.loadtxt('test.txt')

new_data=new_data.reshape((480,910,3))

img = Image.fromarray(new_data,'RGB')
img.save('my.bmp')
img.show()

如果我比较数组(在保存之前和从文件加载和整形之后),数组看起来完全一样(点除外)。前任。

[[[ 48  58  24]
  [ 48  58  24]
  [ 47  57  23]
... 
and 
[[[ 48.  58.  24.]
  [ 48.  58.  24.]
  [ 47.  57.  23.]
  ...

但我得到的图像完全失真。为什么会这样?

【问题讨论】:

标签: python numpy python-imaging-library


【解决方案1】:

经过一番练习,我得到了答案

img = Image.fromarray(new_data.astype(numpy.uint8),'RGB')

【讨论】:

    【解决方案2】:

    您可能对numpy.savetxt 感兴趣。听起来很像您正在尝试构建它。

    还有一个互补的numpy.loadtxt

    如果您向 savetxt 提供以 .gz 结尾的文件名,它甚至会压缩数据。 loadtxt 的理解是一样的。

    这适用于任意 numpy 数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-05
      • 2011-06-20
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多