【问题标题】:Convert Matplotlib figure to NumPy array without any borders/frame or axis将 Matplotlib 图形转换为没有任何边框/框架或轴的 NumPy 数组
【发布时间】:2011-12-26 00:25:24
【问题描述】:

我正在尝试将 Python 中生成的图像与文件中的图像/照片进行比较。

到目前为止,我做到这一点的最佳方法是在 Matplotlib 中生成一个图形,然后将其转换为一个 numpy 数组,并将这些值与我从图像中获得的值进行比较。

我得到以下代码来将 Matplotlib 图形转换为具有 RGB 通道的 3D numpy 数组:

def fig2data ( fig ):
    """
    @brief Convert a Matplotlib figure to a 3D numpy array with RGB channels and return it
    @param fig a matplotlib figure
    @return a numpy 3D array of RGB values
    """
    # draw the renderer
    fig.canvas.draw ( )

    # Get the RGBA buffer from the figure
    w,h = fig.canvas.get_width_height()
    buf = numpy.fromstring ( fig.canvas.tostring_rgb(), dtype=numpy.uint8 )
    buf.shape = ( w, h, 3 )

    return buf

其中一个问题 - 到目前为止我试图弄清楚的问题 - 是这个转换后的图像没有被裁剪。例如,如果我绘制一个占据所有画布的正方形,Matplotlib 会将这个烦人的框架环绕起来,然后将其转换并混合我所有的结果。

如何仅获取我制作的图形的数值(没有任何框架或轴)?

或者更好,如果有更简单的方法来比较我不知道的 NumPy/Matplotlib 中的图形和图像,请告诉我。

【问题讨论】:

  • 另外一个问题是fig.canvas.tostring_rgb不兼容python 3...

标签: python image matplotlib figure


【解决方案1】:

嗯,使用 Matplotlib 并不能真正解决手头的问题,但我放弃了这个库来完成这项工作,只使用了 PIL。

这很容易,虽然它也很慢(但我不知道它是否比 Matplotlib 慢)。

代码如下:

def makeImage (triangle, largura, altura):
    """
    triangle: receives a tuple in the form: x1, y1, x2, y2, x3, y3, R, G, B, A
    largura: image weight
    altura: image height

    returns: numPy array of the triangle composed final image
    """
    back = Image.new('RGBA', (largura,altura), (0,0,0,0))
    poly = Image.new('RGBA', (largura,altura))
    pdraw = ImageDraw.Draw(poly)

    pdraw.polygon([1,2,3,4,5,6], fill=(255,0,0,127))
    back.paste(poly,mask=poly)

    back = back.convert('RGB')
    backArr = asarray(back)
    #back.show()

    return backArr

如果您知道加快此过程的方法,请告诉我。

【讨论】:

    猜你喜欢
    • 2019-09-06
    • 2018-06-11
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2013-01-28
    相关资源
    最近更新 更多