2012-04-08 77 views
2

我使用Python和Matplotlib進行繪製。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

+1和這個問題的明星。請注意,如果您在之前詢問的7個問題中標記了儘可能多的答案,這將非常有用。這會給人們更多的動力來花時間來回答這個問題以及下面的問題。 – EOL 2012-04-08 14:15:45

回答

4

最簡單的解決方案是首先計算輸入數據的RGBA顏色,對其進行處理以便設置與特殊顏色(綠色)不同的值,然後使用修改過的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') 

,數組x之間的差異,現在y是綠色的數據點: 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') 
+0

謝謝。有用。還剩下一件事,我該如何設定綠點的透明度? – blueSurfer 2012-04-10 10:18:47

+0

好吧,我做到了,我只是添加下面一行: diff_points [x!= y,3] = 0.8 再次感謝您 – blueSurfer 2012-04-10 10:46:00

+0

@ user950625:感謝您接受此答案。如果更好地使用'diff_points [x!= y] = [0,1,0,0.8]'來設置綠色點的透明度:4個值是您的點之間的RGB值和alpha值'x'和'y'數組。 – EOL 2012-04-10 12:17:47

0

另一個可能的方式是改變colorma p以便以不同的方式顯示某些值,

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

此方法的一個優點是可以稍後重新使用此顏色映射。