1

I'm looking for away to directly convert my 2D array to the RGB data of matplotlib's matshow() method. What I've acknowledged from the source code is that it uses imshow() method, which sets some hyperparameters and then calls add_image(), in which based on https://github.com/matplotlib/matplotlib/blob/1722bfd6ae4fac707811c8e8dca171138cb5d2a6/lib/matplotlib/axes/_base.py calls append(image). And I'm stuck from this.

So, is there any way to directly map a raw 2D array to image RGB array after matshow() method (with colormap integrated) without calling the plotting?

Edit: In case that my above explanation is hard to understand, I have a 2D matrix (not a grayscale image array). I'm gonna plot it using matshow() with a certain colormap, and vmin & vmax values. I can extract the image pixel values as a 3D array using fig.canvas.show() and np.fromstring() as in here. However my application has very strict time constraint that plotting the data would take too much time (and also very unstable). So instead of plotting (which sequentially call figure(), subplot(), matshow()...) I want to get the 3D image data directly (through some mapping) from my original 2D matrix. I believe it is possible if I understand how pyplot maps the data, but unfortunately I couldn't find the solution in their source code yet.

  • So you're having grayscale and want to convert to RGB? You can use `np.repeat(img[..., None], 3, axis=-1)`, does that solve your problem? Or do you want something else? – a_guest Jul 31 '19 at 21:09
  • So you want to save a 2D array as an image? Please elaborate on the constraints of your problem because it is too ambiguous as it stands. – Dodge Jul 31 '19 at 21:18
  • 2
    If you have a colormap, say `plt.cm.viridis` and want to apply it to a normalized array `a`, you call `plt.cm.viridis(a)`. If `a` isn't normalized yet, you can use `norm = plt.Normalize(vmin,vmax)` and call `plt.cm.viridis(norm(a))`. – ImportanceOfBeingErnest Jul 31 '19 at 21:18
  • Guys, I just edited the question to elaborate my intention of doing this. Please have a look. – EternaLCompleX Aug 01 '19 at 02:14
  • @ImportanceOfBeingErnest The result looks like a float array, how to convert this to RGB image array (with value 0 -> 255)? – EternaLCompleX Aug 01 '19 at 02:39
  • The float array from @ImportanceOfBeingErnest's method is constrained between [0,1]. So just multiply the whole array with 255 and convert to int. – JimmyOnThePage Aug 01 '19 at 03:15
  • 1
    This method will result in a RGBA-mapping though, so you will have to drop the alpha-column manually – JimmyOnThePage Aug 01 '19 at 03:15
  • @JimmyOnThePage I think you need `floor(result * 256)`, and then replace any occuance of 256 with 255. Else you loose dynamic range; but I'm not 100% sure. – ImportanceOfBeingErnest Aug 01 '19 at 11:49
  • Thanks guys, the method works nicely :) – EternaLCompleX Aug 01 '19 at 17:56

0 Answers0