2016-03-08 46 views
0

我想要一個matplotlib數字作爲3維RGBA數組。我使用以下代碼來執行轉換:python matplotlib figure into rgba array

%matplotlib inline 

import matplotlib.pyplot as plt 
import numpy as np 

canvas = np.zeros((20, 20)) 

img = plt.imshow(canvas, interpolation='none').make_image() 
h, w, d = img.as_rgba_str() 
print(h,w) 
rgba_array = np.fromstring(d, dtype=np.uint8).reshape(h, w, 4) 

plt.imshow(rgba_array) 

Out[1]: (249, 373) 
<matplotlib.image.AxesImage at 0x111fa8b10> 

output from cell

爲什麼從原始正方形陣列的縱橫比的變化?有沒有我可以指定的參數,或者是否有一個可以使圖形的rgba數組處於原始形狀的方法?

回答

0

我找到了一種替代方法,不使用的.imshow()函數,並且保留大小比:

%matplotlib inline 

import matplotlib.pyplot as plt 
import numpy as np 
from PIL import Image 

canvas = np.zeros((20, 20)) 
img = Image.fromarray(np.uint8(plt.cm.gist_earth(canvas)*255)) 
rgba_array = np.array(img.getdata(), np.uint8).reshape(img.size[1], img.size[0], 4) 
print(rgba_array.shape) 

plt.imshow(rgba_array) 

Out[1]: (20, 20, 4) 
<matplotlib.image.AxesImage at 0x112a71710> 

enter image description here

0

當我在pycharm 執行代碼(353,497) 當我在由線 pycharm線執行代碼(353,353) 當我在IPython的執行代碼(從命令殼) (385 ,497)

我假定

img = plt.imshow(canvas, interpolation='none').make_image() 
h, w, d = img.as_rgba_str() 

make_image()實際上未轉化的值,但在軸的每個像素的一個值。所以如果你的座標軸在屏幕上顯示爲正方形,它將以更高的分辨率選擇一個正方形。否則就是一些矩形,這取決於你的後端和屏幕分辨率。

0

我覺得你可以到那裏用這個回答:https://stackoverflow.com/a/35362787/1072212,但不是canvas.tostring_rgb()使用canvas.tostring_argb()(不..._rgba())和

width, height = map(int, fig.get_size_inches() * fig.get_dpi()) 
image = image.reshape(height, width, 4) 
image = np.roll(image, -1, 2) 

稍後您可能需要

img = Image.fromarray(image, 'RGBA') 
img.save('my.png') 
img.show()