将matplotlib图形转换为相同形状的numpy数组

时间:2019-04-16 07:49:11

标签: python arrays numpy matplotlib

我有一个256x256的图片,我希望能够绘制通过这些点的回归线。为此,我将图像转换为散点图,然后尝试将散点图转换回numpy数组。但是,转换回numpy数组会使numpy数组变为480x640。

请问有人可以向我解释为什么形状发生变化,主要是为什么它不再是正方形图像,以及是否有任何转换方法可以解决?

从二进制图像中获取x点和y点

imagetile = a[2]
x, y = np.where(imagetile>0)
imagetile.shape

输出:(256公升,256公升)

版本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)

谢谢

1 个答案:

答案 0 :(得分:1)

如果在不设置参数figsize的情况下调用matplotlib.pyplot.figure,它将采用默认形状(文档中的引号):

  

figsize :(浮动,浮动),可选,默认设置:无宽度,高度   英寸。如果未提供,则默认为rcParams [“ figure.figsize”] =   [6.4,4.8]。

因此,您可以通过

设置形状
matplotlib.pyplot.figure(figsize=(2.56,2.56))

不知道您的数据是什么样子,我认为您的方法相当round回,所以,我建议这样:

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()

link to the documentation of np.polyfit