I have an 256x256 image and I want to be able to plot a regression line through the points. To do this I converted the image to a scatter plot and then tried to convert the scatter plot back to a numpy array. However, conversion back to a numpy array made the numpy array 480x640.
Would anyone please be able to explain to me why the shape changes, mainly why it's no longer a square image, and if there's any conversion to fix it?
Making my x and y points from binary image
imagetile = a[2]
x, y = np.where(imagetile>0)
imagetile.shape
Out: (256L, 256L)
Version 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
Out: (480L, 640L, 4L)
Version 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
Out: (640L, 480L, 4L)
Thank you