You are looking for the colormap that is used by the image created via imshow
. Now of course you can reverse engineer how that colormap got into the image in the first place like the other answer suggests. That seems cumbersome and often enough isn't even possible.
So given an AxesImage
(the object returned by imshow
) or for that matter any other ScalarMappable
, you get the colormap in use via .cmap
. Since the data values are normalized to the range between 0..1, you need a normalization, which you get from the .norm
attribute. Finally, you need the data, which you get from the .get_array()
method.
The magic_function
is hence a chain of three functions.
im = plt.imshow(np.random.rand(10, 10))
color_matrix = im.cmap(im.norm(im.get_array()))
color_matrix
is now the (10, 10, 4)-shaped RGBA array of colors corresponding to the pixels in the image.