使用切片将特定颜色替换为黑色吗?

问题描述 投票:0回答:1

第一次问一个关于stackoverflow的问题!我正在尝试使用切片替换特定的像素颜色。我有兴趣将粉红色替换为黑色。

 colors = [(0, 0, 0), (255, 0, 255)]
 img = cv2.imread('Untitled.png')  # Random image containing some pink pixels
 pink = img[:, :, :] == np.array(colors[1])  # Boolean array with TRUE @ all pink indices

当我尝试使用此功能进行更换时

img[pink, :] = np.array(colors[0])  # Replace with black

我收到以下错误

img[pink, :] = np.array(colors[0])
IndexError: too many indices for array

img和粉红色是相同的尺寸和大小。我在做什么错?

python replace colors slice pixel
1个回答
1
投票

这应该为您工作:

import cv2

image = cv2.imread('test.png')
image[np.where((image==[255,0,255]).all(axis=2))] = [0,0,0]
cv2.imwrite('test_out.png', image)
© www.soinside.com 2019 - 2024. All rights reserved.