sololuvr99
sololuvr99

Reputation: 73

Replace color in numpy image with another color

I have two colors, A and B. I want to swap A and B with eachother in the image.

So far what I have written is:

    path_to_folders = "/path/to/images"
    tifs = [f for f in listdir(path_to_folders) if isfile(join(path_to_folders, f))]
    for tif in tifs:
        img = imageio.imread(path_to_folders+"/"+tif)
        colors_to_swap = itertools.permutations(np.unique(img.reshape(-1, img.shape[2]), axis=0), 2)
        for colors in colors_to_swap:
            new_img = img.copy()
            new_img[np.where((new_img==colors[0]).all(axis=2))] = colors[1]
            im = Image.fromarray(new_img)
            im.save(path_to_folders+"/"+tif+"-"+str(colors[0])+"-for-"+str(colors[1])+".tif")

However nothing is changed in the images saved to disk. What am I doing wrong?

Upvotes: 3

Views: 2773

Answers (3)

Greg7000
Greg7000

Reputation: 425

Here is an example which might be simplier to read:

# Show a 2x2 red image  with a blue  dot (RGB)
image = np.ones((2, 2, 3), dtype=np.uint8)
image[:, :] = [255, 0, 0]
image[0, 0] = [0, 0, 255]
plt.imshow(image)
plt.show()

# Create a mask where the red condition is True
mask = np.all(image == [255, 0, 0], axis=-1)

# Use the mask to change the color where the condition is True
image[mask] = [0, 255, 0]

# Show a 2x2 green image with a blue  dot (RGB)
plt.imshow(image)
plt.show()

Upvotes: 2

bb1
bb1

Reputation: 7863

As far as I can tell your code replaces color A with color B. You should see a change in images, but not a swap of colors: color A should be gone and color B should appear in its place.

To swap two colors you can try, for example, the following. Create a sample image:

import numpy as np
import matplotlib.pyplot as plt

img = np.zeros((12, 12, 3))
col1 = [1, 0, 0]
col2 = [0, 1, 0]
col3 = [0, 0, 0]
img[:] = col1
img[3:9, 3:9] = col3
img[4:8, 4:8] = col2
plt.imshow(img)

This gives:

image

Swap col1 with col2 (i.e. red with green):

mask = [(img == c).all(axis=-1)[..., None] for c in [col1, col2]]
new_img = np.select(mask, [col2, col1], img)
plt.imshow(new_img)

Result:

image with swapped colors

Upvotes: 0

Dani Reinon
Dani Reinon

Reputation: 75

What about this, based on this solution

import numpy as np
from PIL import Image

im = Image.open('fig1.png')
data = np.array(im)

r1, g1, b1 = 0, 0, 0 # Original value
r2, g2, b2 = 255, 255, 255 # Value that we want to replace it with

red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask1 = (red == r1) & (green == g1) & (blue == b1)
mask2 = (red == r2) & (green == g2) & (blue == b2)
data[:,:,:3][mask1] = [r2, g2, b2]
data[:,:,:3][mask2] = [r1, g1, b1]

im = Image.fromarray(data)
im.save('fig1_modified.png')

Upvotes: 1

Related Questions