我有一个 256x256 的图像,我希望能够通过这些点绘制一条回归线。为此,我将图像转换为散点图,然后尝试将散点图转换回 numpy 数组。但是,转换回 numpy 数组会使 numpy 数组变为 480x640。
谁能向我解释为什么形状会发生变化,主要是为什么它不再是方形图像,以及是否有任何转换可以修复它?
从二进制图像制作我的 x 和 y 点
imagetile = a[2]
x, y = np.where(imagetile>0)
imagetile.shape
输出:(256L,256L)
版本 1
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)
版本 2
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)
谢谢
慕工程0101907
相关分类