为什么我在Windows上从Pillow获得"Not Enough Image Data",而相同的代码在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: %snnCannot 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: %snnCannot 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:Python27libsite-packagesPILImage.py", line 2100, in frombytes
    im.frombytes(data, decoder_name, args)
  File "C:Python27libsite-packagesPILImage.py", line 742, in frombytes
    raise ValueError("not enough image data")
ValueError: not enough image data

你知道怎么了?多谢。

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

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


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

最新更新