I have an image I load into python using matplotlib.pyplot.imread which ends up as an numpy array containing an array of rgb values. Here is a dummy snippet with all but two pixel white:
>>> test
array([[[255, 255, 255],
[255, 255, 255]],
[[ 1, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 6, 255]]], dtype=uint8)
I want to create a mask out all the white pixels. I think I could do something similar to
>>> mask = (test != [255, 255, 255])
which would give:
array([[[False, False, False],
[False, False, False]],
[[ True, True, True],
[False, False, False]],
[[False, False, False],
[ True, True, True]]], dtype=bool)
How do I do this?
Alternatively, I would think there is an input parameter for imshow which does this but the documentation is not clear how. It seems alpha would change the entire image and vmax accepts a scaler which does not seem compatible with RGB colors.
One option would be to construct a masked array and then imshow it:
import numpy as np
from matplotlib import pyplot as plt
x = np.array([[[255, 255, 255],
[255, 255, 255]],
[[ 1, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 6, 255]]], dtype=np.uint8)
mask = np.all(x == 255, axis=2, keepdims=True)
# broadcast the mask against the array to make the dimensions the same
x, mask = np.broadcast_arrays(x, mask)
# construct a masked array
mx = np.ma.masked_array(x, mask)
plt.imshow(mx)
Masked values will be rendered transparent.
Another option would be to convert your RGB array to an RGBA array, with the alpha channel set to zero wherever the red, green and blue channels are all equal to 255.
alpha = ~np.all(x == 255, axis=2) * 255
rgba = np.dstack((x, alpha)).astype(np.uint8)
plt.imshow(rgba)
Note that I had to cast rgba back to uint8 after the concatenation, since imshow expects RGBA arrays to either be uint8 or float.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With