Issue
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?
Solution
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:
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:
Answered By - bb1
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.