Plotting an irregularly-spaced RGB image in Python

后端 未结 2 816
忘了有多久
忘了有多久 2020-12-06 14:08

I want to plot several RGB images on one set of axes with matplotlib. I initially tried using imshow for this, but it doesn\'t seem to handle two images on one set of axes

相关标签:
2条回答
  • 2020-12-06 14:51

    How about combining all your images into one big numpy array which you then display with imshow?

    0 讨论(0)
  • 2020-12-06 14:55

    The solution was very simple: the one thing I needed to do that wasn't in the question I linked to was to remove the array from the mesh object. A minimal example, in case it's helpful to others:

    import numpy as np
    import matplotlib.pyplot as plt
    
    #make some sample data
    r, g = np.meshgrid(np.linspace(0,255,100),np.linspace(0,255,100))
    b=255-r
    
    #this is now an RGB array, 100x100x3 that I want to display
    rgb = np.array([r,g,b]).T
    
    color_tuple = rgb.transpose((1,0,2)).reshape((rgb.shape[0]*rgb.shape[1],rgb.shape[2]))/255.0
    
    m = plt.pcolormesh(r, color=color_tuple, linewidth=0)
    m.set_array(None)
    plt.show()
    

    I guess the color_tuple line might be non-obvious: essentially we need to turn the (n, m, 3) array into an (n*m, 3) array. I think the transpose is necessary to get everything to match up correctly. It's also worth noting that the colors we pass in need to be floating-point, between 0 and 1.

    0 讨论(0)
提交回复
热议问题