我正在尝试检索由imshow()函数生成的matplotlib热图上每个单元格的颜色,例如由以下magic_function执行的操作:
I am trying to retrieve the colors of each cell on a matplotlib heatmap, generated by the imshow() function, such as performed by the magic_function below:
import matplotlib.pyplot as plt import numpy as np hm = plt.imshow(np.random.rand(10, 10)) color_matrix = hm.magic_function() #returns matrix containing the RGB/Hex values of each cell推荐答案
您正在寻找通过imshow创建的图像所使用的色图.现在,当然,您可以像其他答案所建议的那样,逆向工程该颜色图如何首先进入图像.这似乎很麻烦,而且通常甚至不可能.
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.
因此,给定一个AxesImage(由返回的对象)或就其他任何ScalarMappable而言,您可以通过.cmap使用该色图.由于数据值已归一化到0..1之间的范围,因此需要归一化,该归一化是从.norm属性获得的.最后,您需要从.get_array()方法获得的数据.
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.
magic_function因此是由三个功能组成的链.
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现在是与图像中像素相对应的(10、10、4)形状的RGBA颜色数组.
color_matrix is now the (10, 10, 4)-shaped RGBA array of colors corresponding to the pixels in the image.
更多推荐
检索Matplotlib热图颜色
发布评论