Matplotlib:绘制两幅图像之间的差异

时间:2012-04-08 14:04:50

标签: python image matrix matplotlib

我正在使用Python和Matplotlib进行绘图。

我有两个矩阵(图像为灰色),如下所示:

x = np.array([[0,1,0], [1,0,1]])
y = np.array([[0,0.4,0], [1,0,1]])

我想绘制一个新图像z,它显示x和y之间的差异(比如说绿点),并将其他点保留为灰度等级。所以,在前面的例子中,如果1是黑色而0是白色,则z应该是一个相同的图像,绿色点对应于x和y之间的差异(在这种情况下为0.4)。

这样做的目的是在手写数据图像中设置k-means算法的动画,以观察算法的工作方式。

我希望这很清楚,对不起我的英语。

2 个答案:

答案 0 :(得分:4)

最简单的解决方案是首先计算输入数据的RGBA颜色,对其进行操作以设置与特殊颜色(绿色)不同的值,然后使用简单的imshow()绘制修改后的RGBA阵列。以下是如何做到这一点:

>>> rgba_values = cm.gray(y)  # All RGBA values for your input value, with levels of gray
>>> rgba_values[x != y] = [0, 1, 0, 1]  # Set the points where x and y differ to green (RBG = 0, 1, 0)
>>> imshow(rgba_values, interpolation='nearest')

数组xy之间不同的数据点现在为绿色: image with the common data in gray and the differences in green

如果要在先前显示的图像上叠加绿点,可以执行类似操作并将Alpha通道设置为0,以便您不想修改原始图像:

>>> y_gray = cm.gray(y)  # RGBA image with gray levels
>>> imshow(y_gray, interpolation='nearest')  # Image of one of the arrays
>>> diff_points = numpy.empty_like(y_gray)  # Preparation of an overlay with marked points only
>>> diff_points[x == y, 3] = 0  # Common points not overwritten: alpha layer set to 0
>>> diff_points[x != y] = [0, 1, 0, 1]  # Green for points that differ
>>> imshow(diff_points, interpolation='nearest')

答案 1 :(得分:0)

另一种可能的方法是改变色彩映射以便以不同的方式显示某些值,

import matplotlib.cm, matplotlib.pyplot as plt, numpy as np, copy
x = np.array([[0,1,0], [1,0,1]])
y = np.array([[0,0.4,0], [1,0,1]])
y_mod = y.copy()
y_mod[x != y] = np.nan # filling the differing pixels with NaNs    
xcm = copy.copy(matplotlib.cm.gray) # copying the gray colormap
xcm.set_bad(color='green', alpha=0.5) # setting the color for "bad" pixels"
plt.imshow(y_mod, cmap=xcm, interpolation='none')

这种方法的一个优点是,您可以稍后重复使用此颜色图。

相关问题