2016-02-29 70 views
3

我想創建一個矩陣子圖並在一個不同的子圖中顯示每個BMP文件,但是我找不到適合我的問題的解決方案,有人可以幫助我嗎?在matplotlib子圖中繪製幾個圖像文件

這是我的代碼:

import os, sys 
from PIL import Image 
import matplotlib.pyplot as plt 
from glob import glob 

bmps = glob('*trace*.bmp') 

fig, axes = plt.subplots(3, 3) 

for arch in bmps: 
    i = Image.open(arch) 
    iar = np.array(i) 
    for i in range(3): 
     for j in range(3): 
      axes[i, j].plot(iar) 
      plt.subplots_adjust(wspace=0, hspace=0) 
plt.show() 

我有執行後出現以下錯誤:

enter image description here

回答

7

本身matplotlib只支持PNG圖像,請參閱http://matplotlib.org/users/image_tutorial.html

然後方式總是閱讀圖像 - 繪製圖像

讀取圖像

img1 = mpimg.imread('stinkbug1.png') 
img2 = mpimg.imread('stinkbug2.png') 

情節圖像(2副區)

plt.figure(1) 
plt.subplot(211) 
plt.imshow(img1) 

plt.subplot(212) 
plt.imshow(img2) 
plt.show() 

遵循http://matplotlib.org/users/image_tutorial.html教程(因爲導入庫)

這裏是一個使用matplotlib繪製bmp的線程:Why bmp image displayed as wrong color with plt.imshow of matplotlib on IPython-notebook?

+0

拉爾夫,感謝您的回覆。如果我理解你的答案,我需要將格式從BMP更改爲PNG,然後再次運行我的代碼?你沒有提到我的代碼,如果我有PNG,而不是BMP,你認爲我的代碼將運行?再次感謝。 – hammu

+0

第一次嘗試我會保持簡單,就像在http://matplotlib.org/1.3.1/users/pyplot_tutorial.html#pyplot-tutorial和上面的帖子。如果它工作,你可以添加更復雜的功能 –

0

bmp有三個顏色通道,加上高度和寬度,給它一個(h,w,3)的形狀。我相信繪製圖像會給你一個錯誤,因爲該圖只接受兩個維度。你可以灰度圖像,這將產生一個只有兩個維度(h,w)的矩陣。

不知道該圖像的尺寸,你可以做這樣的事情:

for idx, arch in enumerate(bmps): 
    i = idx % 3 # Get subplot row 
    j = idx // 3 # Get subplot column 
    image = Image.open(arch) 
    iar_shp = np.array(image).shape # Get h,w dimensions 
    image = image.convert('L') # convert to grayscale 
    # Load grayscale matrix, reshape to dimensions of color bmp 
    iar = np.array(image.getdata()).reshape(iar_shp[0], iar_shp[1]) 
    axes[i, j].plot(iar) 
plt.subplots_adjust(wspace=0, hspace=0) 
plt.show() 
+0

布賴恩,如果我用你的建議運行它似乎進程進入無限循環(內存錯誤) – hammu

+0

我認爲你的兩個嵌套循環有問題。請參閱上面修改的代碼片段。 –

+0

您好,Brian,經過幾次試驗後,我無法獲得我想要的結果,我將格式文件更改爲JPG,現在我的列表「bmps」包含了我的JPG文件,在運行您的建議後,我得到以下消息:IndexError:索引2超出大小爲2的軸0的界限 – hammu