blueSurfer
blueSurfer

Reputation: 5821

Matplotlib: plot differences between two images

I'm using Python with Matplotlib for drawing.

I have two matrices (images in levels of gray) like this:

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

I want to plot a new image z which show the differences (as let's say green points) between x and y and leave the other points in scale of grays. So, in the previous example if 1 is black and 0 is white, z should be an identical image with a green point in correspondence to the difference between x and y (in this case 0.4).

The purpose of this is to animate the k-means algorithm execution in the handwritten data images to watch how the algorithm is working.

I hope this is clear, sorry for my English.

Upvotes: 3

Views: 3086

Answers (2)

sega_sai
sega_sai

Reputation: 8538

One other possible way is to alter the colormap in order to show certain values differently,

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

One advantage of this approach is that you can then reuse this colormap later.

Upvotes: 0

Eric O. Lebigot
Eric O. Lebigot

Reputation: 94485

The simplest solution consists in calculating the RGBA colors of your input data first, manipulating it so as to set the values that differ to your special color (green), and then plotting with a simple imshow() the modified RGBA array. Here is how this can be done:

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

The data points that differ between arrays x and y are now in green: image with the common data in gray and the differences in green

If you want to overlay your green points on an image previously displayed, you can do something similar and set the alpha channel to 0 where you don't want to modify your original image:

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

Upvotes: 4

Related Questions