繁体   English   中英

为什么我在 Windows 上从 Pillow 获得“Not Enough Image Data”,而相同的代码在 Linux 上运行良好?

[英]Why do I get "Not Enough Image Data" from Pillow on Windows, while the same code works well on Linux?

我们正在尝试将在 Linux 上运行良好的家庭作业的支持文件移植到 Windows。 一部分作业要求学生操作原始图像数据,支持文件使用 Python 在原始数据和图像文件之间进行转换。 将图像文件转换为原始数据的代码是:

import os, sys
from PIL import Image
from struct import *

fileName = sys.argv[1]
try:
    myImg = Image.open(fileName)
    width,height = myImg.size
    sys.stdout.write(pack("ii",width,height))
    rgbImg = myImg.convert("RGB")
    pixels = rgbImg.getdata()
    for (r,g,b) in pixels:
        sys.stdout.write(pack("BBB", r,g,b)) 
except IOError, e:
    print >> sys.stderr, "%s: %s\n\nCannot open or understand %s" % (sys.argv[0], str(e), fileName)

而转换回来的代码是:

import os, sys
from PIL import Image
from struct import *

fileName = sys.argv[1]
try:
    dimensions = sys.stdin.read(2*4)
    width,height = unpack("ii", dimensions)

    pixels = sys.stdin.read(3*width*height)
    myImg = Image.frombytes("RGB", (width, height), pixels, "raw", "RGB", 0, 1)
    myImg.save(fileName, "PNG")
except IOError, e:
    print >> sys.stderr, "%s: %s\n\nCannot open or write to %s" % (sys.argv[0], str(e), fileName)

标准输出和输入被重定向到测试设施代码中的文件。 该代码在 Linux 上运行良好,但在 Windows 上运行不佳。 尝试在 Windows 上写入图像文件时,我们总是会收到以下错误:

Traceback (most recent call last):
  File "image-rewrite.py", line 16, in <module>
    myImg = Image.frombytes("RGB", (width, height), pixels, "raw", "RGB", 0, 1)
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 2100, in frombytes
    im.frombytes(data, decoder_name, args)
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 742, in frombytes
    raise ValueError("not enough image data")
ValueError: not enough image data

你知道发生了什么吗? 非常感谢。

在 Windows 上使用stdin / stdout传输二进制数据是一个坏主意。 Windows 使用 CRLF ( '\\r\\n' ) 作为行尾标记,并在输入时转换为\\n并在输出时转换回; 翻译过程可能会对二进制数据造成严重破坏。

相反,您应该使用命名文件,并以二进制模式打开它们。


顺便说一句,在 Python 3 中,即使在 Linux 上,您也无法直接从 / 向sys.stdin / sys.stdout读取/写入二进制数据。 相反,您需要使用sys.stdin.buffer / sys.stdout.bufferread / write方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM