我想在Python 2.7,打開一個JPEG文件,閱讀在Python(PIL)一個JPEG頭損壞
from PIL import Image
im = Image.open(filename)
這並沒有爲我工作,
>>> im = Image.open(filename)
Traceback (most recent call last):
File "<pyshell#810>", line 1, in <module>
im = Image.open(filename)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1980, in open
raise IOError("cannot identify image file")
IOError: cannot identify image file
雖然當試用外部觀衆時,它打開罰款。在挖掘一下,事實證明,從PIL
的JpegImagePlugin.py
文件JpegImageFile._open
方法提出了SyntaxError
例外由於JPEG的文件頭中0xFFDA
標誌之前幾個外來0x00
字節,
Corrupt JPEG data: 5 extraneous bytes before marker 0xda
也就是說,其他我嘗試的程序只是簡單地忽略了標題末尾的未知0x00
標記,PIL
最好引發異常,不允許我打開圖像。
問題:除了直接編輯0的代碼,是否有任何解決方法來打開有問題標題的JPEG?
從JpegImageFile
類引發異常相關的代碼顯示如下,爲了您的方便:
def _open(self):
s = self.fp.read(1)
if ord(s[0]) != 255:
raise SyntaxError("not a JPEG file")
# Create attributes
self.bits = self.layers = 0
# JPEG specifics (internal)
self.layer = []
self.huffman_dc = {}
self.huffman_ac = {}
self.quantization = {}
self.app = {} # compatibility
self.applist = []
self.icclist = []
while 1:
s = s + self.fp.read(1)
i = i16(s)
if MARKER.has_key(i):
name, description, handler = MARKER[i]
# print hex(i), name, description
if handler is not None:
handler(self, i)
if i == 0xFFDA: # start of scan
rawmode = self.mode
if self.mode == "CMYK":
rawmode = "CMYK;I" # assume adobe conventions
self.tile = [("jpeg", (0,0) + self.size, 0, (rawmode, ""))]
# self.__offset = self.fp.tell()
break
s = self.fp.read(1)
elif i == 0 or i == 65535:
# padded marker or junk; move on
s = "\xff"
else:
raise SyntaxError("no marker found")
Thanks @Hugo!每當PIL引發異常時,我最終都會使用OpenCV克服自己的問題。很高興知道PIL正在發展中...... –