【问题标题】:Matplotlib: plot differences between two imagesMatplotlib:绘制两个图像之间的差异
【发布时间】:2012-04-08 14:04:50
【问题描述】:

我正在使用 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 算法执行动画,以观察算法是如何工作的。

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

【问题讨论】:

  • +1 并为这个问题加星。请注意,如果您在之前提出的 7 个问题中将尽可能多的答案标记为已接受,这将很有用。这将激励人们花时间回答这个问题以及以下问题。

标签: python image matrix matplotlib


【解决方案1】:

最简单的解决方案是首先计算输入数据的 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 之间不同的数据点现在显示为绿色:

如果您想在之前显示的图像上叠加绿点,您可以执行类似的操作并将 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')

【讨论】:

  • 谢谢。有用。只剩下一件事了,如何设置绿点的透明度?
  • 好的,我做到了,我只需添加以下行:diff_points[x != y, 3] = 0.8 再次感谢您
  • @user950625:感谢您接受这个答案。如果使用 diff_points[x != y] = [0, 1, 0, 0.8] 更好地设置绿点的透明度:这 4 个值是您的 xy 数组之间不同点的 RGB 和 alpha(透明度)值。
【解决方案2】:

另一种可能的方法是更改​​颜色图以不同方式显示某些值,

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')

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 2015-01-18
    相关资源
    最近更新 更多