首页 > 解决方案 > 在 matplotlib 中提取叠加 AxesImage 的唯一颜色

问题描述

这是一个关于 matplotlib 图像中颜色信息的问题。

我用以下代码绘制了两个数组:

import numpy as np
import matplotlib.pyplot as plt

M1 = ([1,      2,      3,      np.nan], 
      [4,      5,      np.nan, np.nan], 
      [6,      7,      8,      9])

M2 = ([np.nan, np.nan, np.nan, np.nan],
      [np.nan, 1,      2,      3], 
      [np.nan, 4,      5,      6])

M1arr = ~np.isnan(M1)
M2arr = ~np.isnan(M2)

fig, ax = plt.subplots()

im1 = ax.imshow(M1arr, cmap="Reds",  alpha=0.5)
im2 = ax.imshow(M2arr, cmap="Blues", alpha=0.5)

#color_array = mystery_function(im1, im2, ax, fig) 

plt.show()

输出:
![![在此处输入图像描述

有没有办法从我们最终看到的绘制的复合图像中提取颜色(例如,创建一个颜色条)?我已经看到了如何从or对颜色进行逆向工程的惊人答案。BUT不是我们最终会看到的复合叠加图像,并且似乎只是由. 我还尝试强制 matplotlib 预先生成最终图像并使用 提取图像,可惜这两个图像仍然分开。im1im2im2im1im2plt.show()plt.draw()ax.get_images()

我对如何以不同的方式解决这个问题不感兴趣——在无用的尝试之后,我改变了策略并改为绘制组合矩阵AxesImage我的问题是,如果我们可以在它显示前不久提取四种颜色。
同样有用的是有关 matplotlib 如何组合叠加层中的颜色的信息。我尝试对im1和中的颜色求和im2(显然是错误的,因为它可以超过 1)和每个颜色通道的平均值(也是错误的)。

标签: pythonimagematplotlibcolorsrenderer

解决方案


经过一番挖掘,我找到了如何获取渲染数组的答案。它基于绘制图形,正如我之前尝试过的那样,并使用以下命令检索渲染器缓冲区的内存视图fig.canvas.buffer_rgba()

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors

M1 = ([1,      2,      3,      np.nan], 
      [4,      5,      np.nan, np.nan], 
      [6,      7,      8,      9])

M2 = ([np.nan, np.nan, np.nan, np.nan],
      [np.nan, 1,      2,      3], 
      [np.nan, 4,      5,      6])

M1arr = ~np.isnan(M1)
M2arr = ~np.isnan(M2)

fig, ax = plt.subplots()

ax.imshow(M1arr, cmap="Reds",  alpha=0.5)
ax.imshow(M2arr, cmap="Blues", alpha=0.5)


#get image without axis, so only the colors plotted in the overlay image are considered
ax.axis("off")
#get rgba values from image predrawn by the renderer
fig.canvas.draw()
im = fig.canvas.buffer_rgba()
#identify unique colors, containing white background
all_colors = np.unique(np.asarray(im).reshape(-1, 4), axis=0)
#remove white background color
colors_image = all_colors[:-1].reshape(4, -1)

#turn axes back on
ax.axis("on")
#determine cmap and norm for colorbar
cmapM1M2 = colors.ListedColormap(colors_image[::-1]/255)
normM1M2 = colors.BoundaryNorm(np.arange(-0.5,4), 4) 

#temporarily draw image of zeroes to get scalar mappable for colorbar
temp_im = ax.imshow(np.zeros(M1arr.shape), cmap=cmapM1M2, norm=normM1M2)
cbt = plt.colorbar(temp_im, ticks=np.arange(4), fraction=0.035)
#and remove this temporary image
temp_im.remove()

#label colorbar
cbt.ax.set_yticklabels(["M1 & M2 NaN", "only M1 values", "only M2 values", "M1 & M2 values"])
#and overlay image
ax.set_xticks(np.arange(M1arr.shape[1]))
ax.set_yticks(np.arange(M1arr.shape[0]))

plt.tight_layout()
plt.show()

输出:
在此处输入图像描述

为了在颜色栏中使用已识别的唯一颜色,我绘制了一个临时图像,稍后将其删除。也可以从头开始绘制一个颜色条,但结果是手动控制所有参数相当烦人。

更新
我刚刚注意到不需要颜色条,这在上一个问题中很方便。所以,我们也可以只创建一个带有补丁的图形图例:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

M1 = ([1,      2,      3,      np.nan], 
      [4,      5,      np.nan, np.nan], 
      [6,      7,      8,      9])

M2 = ([np.nan, np.nan, np.nan, np.nan],
      [np.nan, 1,      2,      3], 
      [np.nan, 4,      5,      6])

M1arr = ~np.isnan(M1)
M2arr = ~np.isnan(M2)

fig, ax = plt.subplots()

ax.imshow(M1arr, cmap="Reds",  alpha=0.5)
ax.imshow(M2arr, cmap="Blues", alpha=0.5)

#after this, I want to extract the colors of the overlay image

#get image without axis, so only the colors plotted in the overlay image are considered
ax.axis("off")
#get rgba values from image predrawn by the renderer
fig.canvas.draw()
im = fig.canvas.buffer_rgba()
#identify unique colors, containing white background
all_colors = np.unique(np.asarray(im).reshape(-1, 4), axis=0)
#remove white background color
colors_image = all_colors[:-1].reshape(4, -1)


#turn axes back on
ax.axis("on")
#and overlay image
ax.set_xticks(np.arange(M1arr.shape[1]))
ax.set_yticks(np.arange(M1arr.shape[0]))

#create legend with patches of the four colors
categories = ["M1 & M2 NaN", "only M1 values", "only M2 values", "M1 & M2 values"]
fig.legend(handles=[mpatches.Patch(facecolor=col, edgecolor="k", label=categories[3-i]) for i, col in enumerate(colors_image/255)],
           loc="upper center", ncol = 2)

plt.show()

输出:
在此处输入图像描述

带回家的信息:在绘图之前定义参数比从后端内存中追溯提取信息更容易。


推荐阅读