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