python - 将图像中的所有其他颜色更改为黑色,除了 Python OpenCV/Numpy 中指定的一种颜色

标签 python numpy opencv image-processing

我基本上有一个语义分割蒙版,我想将图像中除一种颜色(道路 - 紫色)之外的所有颜色更改为黑色。

如何在 numpy 或 opencv 中执行此操作?

enter image description here

更新图像 This image has tiny corrupted pixels on it 将代码更改为

import cv2

img = cv2.imread("image.png", cv2.COLOR_RGB2BGR)

 colors = [
  (100, 100, 150),
  (32, 11, 119),
  (70, 70, 70),
  (100, 60, 0),
  (142, 0, 0),
  (255, 255, 255)
]

# colors = np.array(colors)
# all other colors
mask = np.zeros(img.shape[:2], dtype=bool)

for color in colors:   
    mask |= (img == color).all(-1)

img[mask] = (255,255,255)

结果是下面的图像,但仍然有相同的轻微损坏(或添加了我想删除的颜色(只看第一行像素)) enter image description here

最佳答案

你可以试试:

# special color
colors = [ (100, 100, 150), (32, 11, 119), (70, 70, 70), (100, 60, 0), (255, 255, 255) ]


# all other colors
mask = np.zeros(img.shape[:2], dtype=bool)

for color in colors:   
    mask |= (img == color).all(-1)

img[~mask] = (255,255,255)

输出(由 plt.imshow 显示):

enter image description here

关于python - 将图像中的所有其他颜色更改为黑色,除了 Python OpenCV/Numpy 中指定的一种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62269937/

相关文章:

iphone - 更改颜色替换中的亮度

python - 如何用更短和自定义的内容有选择地覆盖 python 帮助(MYclass)中的文本?

python - 在 Python 中使用矩阵向量乘法进行速度优化

python - 一维和二维数组上的 numpy 点

python - 如何使用不均匀子数组作为平铺来平铺一维 numpy 数组?

android - 在 Android 2.3.3 上使用 OpenCv 的 native 代码时引发 UnsatisfiedLinkError

python - 如何使Python的curses覆盖不透明?

python - 用于降维的 Scikit-learn 主成分分析 (PCA)

python - 如何将一个值 append 到列表中的每个元组?

python - Windows 10 上的 opencv python 相机权限问题