【问题标题】:Displaying image from image raw data从图像原始数据显示图像
【发布时间】:2013-11-15 01:31:15
【问题描述】:

使用以下代码从图像中读取像素值后:

import os, sys
import Image

pngfile = Image.open('input.png')
raw = list (pngfile.getdata())

f = open ('output.data', 'w')
for q in raw:
    f.write (str (q) + '\n')
f.close ()

如何在读取以原始格式存储的数据后显示图像?有没有 getdata() 的相反功能来实现这一点?

【问题讨论】:

    标签: python image-processing


    【解决方案1】:

    我不确定你想通过这样做来完成什么,但这是一个将原始图像像素数据保存到文件中的工作示例,将其读回,然后再次从中创建Imageobject .

    请务必注意,对于压缩图像文件类型,此转换将扩大保存图像数据所需的内存量,因为它可以有效地解压缩它。

    from PIL import Image
    
    png_image = Image.open('input.png')
    saved_mode = png_image.mode
    saved_size = png_image.size
    
    # write string containing pixel data to file
    with open('output.data', 'wb') as outf:
        outf.write(png_image.tostring())
    
    # read that pixel data string back in from the file
    with open('output.data', 'rb') as inf:
        data = inf.read()
    
    # convert string back into Image and display it
    im = Image.fromstring(saved_mode, saved_size, data)
    im.show()
    

    【讨论】:

    • 上述代码出现以下错误。回溯(最后一次调用):文件“display_image.py”,第 11 行,在 raw = bytearray(itertools.chain.from_iterable(png_image.getdata())) TypeError: 'int' object is not iterable跨度>
    • 我唯一能想到的可能是图像的类型是因素。我的答案中的代码适用于 24 位 RGB .png 图像。您能否将您正在使用的图片(或图片链接)添加到您的问题中?
    • 我已经添加了图片。
    • 您遇到的问题是因为您的测试图像是灰度的,而我的是RGB颜色。我相信我想出了一种更简单的技术,使用不同的image 模块函数,它也应该能够处理不同的图像文件类型并相应地更新了我的答案。
    【解决方案2】:

    为此,您需要一个 GUI 工具包,或者您需要使用现有的图像显示应用程序。

    This existing SO question 有答案讨论使用Image.show() 和其他方法。

    要从原始数据转为图像,请查看Image.frombuffer()

    【讨论】:

    • 如果你想使用Image.show(),那么我们可以从原始数据文件中创建Image对象吗?
    猜你喜欢
    • 2020-06-08
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多