Getting an RGBA array from a matplotlib image

前端 未结 2 1091
终归单人心
终归单人心 2021-01-24 04:35

I was using imshow to plot an array with a custom colormap and boundarynorm. However, this is going to be an automated script and I want to save the image produced

2条回答
  •  温柔的废话
    2021-01-24 05:18

    You can use as_rgba_str to get the image data from the image. Here's an example:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(0, 2, 1000)
    X, Y = np.meshgrid(x, x)
    data = np.sin((X-2)**3 + Y**4)
    
    im = plt.imshow(data)
    
    x = im.make_image()
    h, w, d = x.as_rgba_str()
    n = np.fromstring(d, dtype=np.uint8).reshape(h, w, 4)
    
    plt.figure()
    plt.imshow(n[:,:,0], cmap="gray", origin='lower')
    
    plt.show()
    

    The original image: enter image description here

    The R channel from the RGBA data (note all the blue sections are black since these have no red in them): enter image description here

提交回复
热议问题