2014-03-24 35 views
4

我想在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 

雖然當試用外部觀衆時,它打開罰款。在挖掘一下,事實證明,從PILJpegImagePlugin.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") 

回答

4

PIL不會在頭喜歡損壞數據,因爲你已經發現翻倒。

我已經向Pillow(友好的PIL分叉)提出了一個拉請求來解決這個問題。

它尚未被接受,但希望它會在幾個月內到期的版本2.5.0。與此同時,你可以在這裏試試:https://github.com/python-imaging/Pillow/pull/647

作爲一種解決方法,你可以使用像ImageMagick之類的東西,首先將有問題的圖像轉換爲png之類的東西,然後在PIL/Pillow中使用它們。

+2

Thanks @Hugo!每當PIL引發異常時,我最終都會使用OpenCV克服自己的問題。很高興知道PIL正在發展中...... –