【问题标题】:python matplotlib figure into rgba arraypython matplotlib图转换为rgba数组
【发布时间】:2016-03-08 06:42:51
【问题描述】:

我想将 matplotlib 图形作为 3 维 RGBA 数组。我正在使用以下代码进行转换:

%matplotlib inline

import matplotlib.pyplot as plt
import numpy as np

canvas = np.zeros((20, 20))

img = plt.imshow(canvas, interpolation='none').make_image()
h, w, d = img.as_rgba_str()
print(h,w)
rgba_array = np.fromstring(d, dtype=np.uint8).reshape(h, w, 4)

plt.imshow(rgba_array)

Out[1]: (249, 373)
<matplotlib.image.AxesImage at 0x111fa8b10>

为什么长宽比与原来的方形阵列不同?有没有我可以指定的参数或替代方法来获取图形的原始形状的 rgba 数组?

【问题讨论】:

    标签: python arrays matplotlib


    【解决方案1】:

    当我在 pycharm 中执行你的代码时 (353, 497) 当我在pycharm中逐行执行你的代码时 (353, 353) 当我在 ipython 中执行您的代码时(从命令外壳) (385, 497)

    我想

    img = plt.imshow(canvas, interpolation='none').make_image()
    h, w, d = img.as_rgba_str()
    

    make_image() 实际上并没有转换值,而是为轴中的每个像素转换一个值。因此,如果您的轴在屏幕上显示为一个正方形,它会选择一个分辨率更高的正方形。否则只是一些矩形,具体取决于您的后端和屏幕分辨率。

    【讨论】:

      【解决方案2】:

      我找到了一种不使用 .imshow() 函数并保留大小比例的替代方法:

      %matplotlib inline
      
      import matplotlib.pyplot as plt
      import numpy as np
      from PIL import Image
      
      canvas = np.zeros((20, 20))
      img = Image.fromarray(np.uint8(plt.cm.gist_earth(canvas)*255))
      rgba_array = np.array(img.getdata(), np.uint8).reshape(img.size[1], img.size[0], 4)
      print(rgba_array.shape)
      
      plt.imshow(rgba_array)
      
      Out[1]: (20, 20, 4)
      <matplotlib.image.AxesImage at 0x112a71710>
      

      【讨论】:

        【解决方案3】:

        我认为你可以使用这个答案到达那里:https://stackoverflow.com/a/35362787/1072212,但不是canvas.tostring_rgb(),而是使用canvas.tostring_argb()(不是..._rgba()),并且

        width, height = map(int, fig.get_size_inches() * fig.get_dpi())
        image = image.reshape(height, width, 4)
        image = np.roll(image, -1, 2)
        

        以后你可能会想要

        img = Image.fromarray(image, 'RGBA')
        img.save('my.png')
        img.show()
        

        【讨论】:

          猜你喜欢
          • 2022-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多