2014-10-30 20 views
1

我正在運行一個python演示,它打算打開一個圖像並可視化其上的對象的分割。這個腳本有一個名爲loadImage()例程用來加載圖像:Matplotlib沒有檢測到正確的文件類型運行時錯誤

def loadImage(self, im_id): 
    """ 
    Load images with image objects. 
    :param im: a image object in input json file 
    :return: 
    """ 
    im = self.images[im_id] 
    return mpimg.imread(open('%s/%s/%s'%(self.image_folder, im['file_path'], im['file_name']), 'r')) 

注意mpimg代表matplotlib(因爲在腳本的開頭行import matplotlib.image as mpimg的)。 然而,一旦腳本執行這個功能,我返回了以下錯誤:

File "script.py", line 148, in callerFunction 
    im = self.loadImage(im_id) 

    File "script.py", line 176, in loadImage 
    return mpimg.imread(open('%s/%s/%s'%(self.image_folder, im['file_path'], im['file_name']), 'r')) 

    File "/usr/lib/pymodules/python2.7/matplotlib/image.py", line 1192, in imread 
    return handler(fname) 

RuntimeError: _image_module::readpng: file not recognized as a PNG file 

我已經做了一些research出於某種原因,它似乎像imread不能正常檢測文件類型時使用打開的文件句柄。因此,由於我試圖加載的圖像是jpgreadpng模塊有運行時錯誤。

可有人請幫我找出:

  1. 這是什麼行爲因?
  2. 什麼是修復?

感謝您的幫助。


@Paul回答並進一步調查後作出的一些澄清。

隨着matplotlib.image documentation稱,該funtion imread()可以接受作爲輸入

a string path or a Python file-like object. If format is provided, will try to read file of that type, otherwise the format is deduced from the filename. If nothing can be deduced, PNG is tried.

,所以我想我的問題應在使用文件句柄作爲輸入導致的是運行時錯誤這種特殊情況下可延長至爲什麼?

回答

1

只給它的文件名:

import os 
import matplotlib.image as mpimg 

class imageThingy(object): 
    def loadImage(self, im_id): 
     """ 
     Load images with image objects. 
     :param im: a image object in input json file 
     :return: 
     """ 
     im = self.images[im_id] 
     imgpath = os.path.join(self.image_folder, im['file_path'], im['file_name']) 
     return mpimg.imread(imgpath) 

    def plotImage(self, im_id): 
     fig, ax = plt.subplots() 
     ax.imshow(img, origin='lower') 
     return fig 

根據文件類型,您可能需要origin="lower"繪製圖像。這是因爲圖像解析器將所有文件類型讀取爲一個numpy數組。 numpy的第一個元素總是總是在右上角。但是,一些文件類型的左上角有他們的原始碼。因此,它們被翻轉爲數組。此信息位於您發佈的鏈接中。

+0

保羅這解決了我的問題!非常感謝。你能告訴我之前發生了什麼,現在發生了什麼變化? – Matteo 2014-10-31 00:53:46

+0

但是仍然有一個東西沒有工作(在我的問題中提到的鏈接中提到),這是圖像結果打印顛倒。你知道如何解決這個問題嗎? – Matteo 2014-10-31 00:55:17

+0

@Matteo第一條評論:你正在傳遞一個文件對象,但'imread'只需要文件的*路徑*。第二條評論我會在我的回覆中解決。 – 2014-10-31 01:01:09

相關問題