Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace color in numpy image with another color

Tags:

python

numpy

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?

like image 839
sololuvr99 Avatar asked Dec 16 '25 21:12

sololuvr99


2 Answers

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()
like image 108
Greg7000 Avatar answered Dec 19 '25 16:12

Greg7000


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')
like image 24
Dani Reinon Avatar answered Dec 19 '25 17:12

Dani Reinon