I am trying to remove a certain color from my image however it\'s not working as well as I\'d hoped. I tried to do the same thing as seen here Using PIL to make all white pi
Using numpy and PIL:
This loads the image into a numpy array of shape (W,H,3)
, where W
is the
width and H
is the height. The third axis of the array represents the 3 color
channels, R,G,B
.
import Image
import numpy as np
orig_color = (255,255,255)
replacement_color = (0,0,0)
img = Image.open(filename).convert('RGB')
data = np.array(img)
data[(data == orig_color).all(axis = -1)] = replacement_color
img2 = Image.fromarray(data, mode='RGB')
img2.show()
Since orig_color
is a tuple of length 3, and data
has
shape (W,H,3)
, NumPy
broadcasts
orig_color
to an array of shape (W,H,3)
to perform the comparison data ==
orig_color
. The result in a boolean array of shape (W,H,3)
.
(data == orig_color).all(axis = -1)
is a boolean array of shape (W,H)
which
is True wherever the RGB color in data
is original_color
.