用另一种颜色替换numpy图像中的颜色

4c8rllxm  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(152)

我有两种颜色,A和B。我想在图像中交换A和B。
到目前为止,我写的是:

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")

字符串
但是,保存到磁盘的图像中没有任何变化。我做错了什么?

9fkzdhlc

9fkzdhlc1#

据我所知,你的代码用颜色B替换了颜色A。你应该看到图像的变化,但不是颜色的交换:颜色A应该消失,颜色B应该出现在它的位置。
要交换两种颜色,您可以尝试以下操作:创建一个示例图像:

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)

字符串
这给出了:


的数据
col1col2交换(即红色与绿色):

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


测试结果:


qqrboqgw

qqrboqgw2#

下面是一个简单的例子:

# 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()

字符串

uubf1zoe

uubf1zoe3#

那么这个呢,基于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')

字符串

相关问题