【问题标题】:How could I filter an image by using a single RGB color?如何使用单一 RGB 颜色过滤图像?
【发布时间】:2020-06-27 11:07:58
【问题描述】:

我是 Python 世界的新手,也是编程新手。我必须完成以下任务:我必须在我的电脑上截取屏幕截图,在 Google 地图交通模式下显示特定区域。

交通信息以 4 种颜色显示。这些颜色是绿色、橙色、红色和较深的红色。通过简单的程序,我可以检查具体的颜色是什么。我的意思是确切的值,例如B: 150, G:100, R:75.

我如何隔离(保持)这种颜色并使所有其他像素变为白色。我已经尝试过使用 HSV 掩码,但效果不是很好。我也尝试过使用 trackbar 和 HSV,结果是一样的。我最常使用 OpenCV、matplotlib、numpy...等。我强调,如果可能的话,我希望使用 rgb 解决方案,例如循环遍历所有像素并仅保留具有特定颜色的像素。谢谢!

我们需要的颜色:

orange      R:255, G:151, B:77
green       R:99,  G:214, B:104
red         R:242, G:60,  B:50
Dark red    R:129, G:31,  B:31

示例

import cv2
import numpy as np
image = cv2.imread('08.00am.Monday.png')
cv2.namedWindow('image', cv2.WINDOW_NORMAL)
lower = np.array([2, 100, 100])
upper = np.array([75, 255, 255])
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower, upper)
output = cv2.bitwise_and(image,image, mask= mask)
cv2.imshow('image',output)
cv2.waitKey(0)
cv2.destroyAllWindows()

example of image

【问题讨论】:

    标签: python image numpy opencv filtering


    【解决方案1】:

    我们可以从使用cv2.inRange() 将每种颜色(红色、绿色、蓝色和深红色)分割到各自单独的蒙版开始,然后我们可以将所有蒙版组合起来生成单个图像,其中所有像素都带有红色、绿色, 蓝色或深红色像素被标记。然后我们可以简单地将输入图像覆盖在我们找到所需像素的白色画布上。你可以看看下面的代码来加深理解:

    import cv2
    import numpy as np
    
    original_image = cv2.imread("/path/to/your/img.png")
    t = 10  # tolerance
    
    orange_thresh = cv2.inRange(original_image, np.array([77 - t, 151 - t, 255 - t]), np.array([77 + t, 151 + t, 255 + t]))
    green_thresh = cv2.inRange(original_image, np.array([104 - t, 214 - t, 99 - t]), np.array([104 + t, 214 + t, 99 + t]))
    red_1_thresh = cv2.inRange(original_image, np.array([50 - t, 60 - t, 242 - t]), np.array([50 + t, 60 + t, 242 + t]))
    red_2_thresh = cv2.inRange(original_image, np.array([31 - t, 31 - t, 129 - t]), np.array([31 + t, 31 + t, 129 + t]))
    
    combined_mask = orange_thresh + green_thresh + red_1_thresh + red_2_thresh
    combined_mask_inv = 255 - combined_mask
    
    combined_mask_rgb = cv2.cvtColor(combined_mask_inv, cv2.COLOR_GRAY2BGR)
    
    final = cv2.max(original_image, combined_mask_rgb)
    
    cv2.imwrite("./debug.png", final)
    

    结果:

    【讨论】:

      猜你喜欢
      • 2011-04-24
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多