我正在運行一個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
不能正常檢測文件類型時使用打開的文件句柄。因此,由於我試圖加載的圖像是jpg
,readpng
模塊有運行時錯誤。
可有人請幫我找出:
- 這是什麼行爲因?
- 什麼是修復?
感謝您的幫助。
@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.
,所以我想我的問題應在使用文件句柄作爲輸入導致的是運行時錯誤這種特殊情況下可延長至爲什麼?
保羅這解決了我的問題!非常感謝。你能告訴我之前發生了什麼,現在發生了什麼變化? – Matteo 2014-10-31 00:53:46
但是仍然有一個東西沒有工作(在我的問題中提到的鏈接中提到),這是圖像結果打印顛倒。你知道如何解決這個問題嗎? – Matteo 2014-10-31 00:55:17
@Matteo第一條評論:你正在傳遞一個文件對象,但'imread'只需要文件的*路徑*。第二條評論我會在我的回覆中解決。 – 2014-10-31 01:01:09