简体   繁体   English

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

[英]Convert matplotlib figure to numpy array of same shape

I have an 256x256 image and I want to be able to plot a regression line through the points. 我有一个256x256的图片,我希望能够通过这些点绘制一条回归线。 To do this I converted the image to a scatter plot and then tried to convert the scatter plot back to a numpy array. 为此,我将图像转换为散点图,然后尝试将散点图转换回numpy数组。 However, conversion back to a numpy array made the numpy array 480x640. 但是,转换回numpy数组会使numpy数组变为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 从二进制图像制作我的x和y点

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

Out: (256L, 256L) 出:(256L,256L)

Version 1 版本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) 出:(480L,640L,4L)

Version 2 版本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) 出:(640L,480L,4L)

Thank you 谢谢

If you call matplotlib.pyplot.figure without setting the argument figsize, it takes on a default shape (quote from the documentation): 如果您在未设置参数figsize的情况下调用matplotlib.pyplot.figure ,它将采用默认形状(文档中的引号):

figsize : (float, float), optional, default: None width, height in inches. figsize :(浮动,浮动),可选,默认设置:无宽度,以英寸为单位的高度。 If not provided, defaults to rcParams["figure.figsize"] = [6.4, 4.8]. 如果未提供,则默认为rcParams [“ figure.figsize”] = [6.4,4.8]。

So, you could set the shape by doing 因此,您可以通过以下方式设置形状

matplotlib.pyplot.figure(figsize=(2.56,2.56))

Not knowing what your data looks like, I think your approach is rather roundabout, so, I suggest something like this: 不知道您的数据是什么样子,我认为您的方法相当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()

link to the documentation of np.polyfit 链接到np.polyfit的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM