![](/img/trans.png)
[英]Convert Matplotlib figure to NumPy array without any borders/frame or axis
[英]Convert matplotlib figure to numpy array of same shape
我有一個256x256的圖片,我希望能夠通過這些點繪制一條回歸線。 為此,我將圖像轉換為散點圖,然后嘗試將散點圖轉換回numpy數組。 但是,轉換回numpy數組會使numpy數組變為480x640。
任何人都可以向我解釋為什么形狀發生變化,主要是為什么它不再是正方形圖像,以及是否有任何固定方法可以修復?
imagetile = a[2]
x, y = np.where(imagetile>0)
imagetile.shape
出:(256L,256L)
from numpy import polyfit
from numpy import polyval
imagetile = a[2]
x, y = np.where(imagetile>0)
from numpy import polyfit
from numpy import polyval
p2 = polyfit(x, y, 2)
fig = plt.figure()
ax = fig.add_axes([0.,0.,1.,1.])
xp = np.linspace(0, 256, 256)
plt.scatter(x, y)
plt.xlim(0,256)
plt.ylim(0,256)
plt.plot(xp, polyval(p2, xp), "b-")
plt.show()
fig.canvas.draw()
X = np.array(fig.canvas.renderer._renderer)
X.shape
出:(480L,640L,4L)
def fig2data ( fig ):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw ( )
# Get the RGBA buffer from the figure
w,h = fig.canvas.get_width_height()
buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )
buf.shape = ( w, h,4 )
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll ( buf, 3, axis = 2 )
return buf
figure = matplotlib.pyplot.figure( )
plot = figure.add_subplot ( 111 )
x, y = np.where(imagetile>0)
p2 = polyfit(x, y, 2)
plt.scatter(x, y)
plt.xlim(0,256)
plt.ylim(0,256)
plt.plot(xp, polyval(p2, xp), "b-")
data = fig2data(figure)
data.shape
出:(640L,480L,4L)
謝謝
如果您在未設置參數figsize的情況下調用matplotlib.pyplot.figure ,它將采用默認形狀(文檔中的引號):
figsize :(浮動,浮動),可選,默認設置:無寬度,以英寸為單位的高度。 如果未提供,則默認為rcParams [“ figure.figsize”] = [6.4,4.8]。
因此,您可以通過以下方式設置形狀
matplotlib.pyplot.figure(figsize=(2.56,2.56))
不知道您的數據是什么樣子,我認為您的方法相當is回,所以,我建議如下所示:
import numpy as np
import matplotlib.pyplot as plt
# generating simulated polynomial data:
arr = np.zeros((256, 256))
par = [((a-128)**2, a) for a in range(256)]
par = [p for p in par if p[0]<255]
arr[zip(*par)] = 1
x, y = np.where(arr>0)
p2 = np.polyfit(y, x, 2)
xp = np.linspace(0,256,256)
plt.imshow(arr) # show the image, rather than the conversion to datapoints
p = np.poly1d(p2) # recommended in the documentation for np.polyfit
plt.plot(xp, p(xp))
plt.ylim(0,256)
plt.xlim(0,256)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.