【问题标题】:Color Detection And Comaparision In PythonPython中的颜色检测和比较
【发布时间】:2019-09-12 06:28:06
【问题描述】:

我想弄清楚图像中是否存在特定颜色?我想编写一个 Python 代码来将给定的颜色值与图像特定位置坐标中的颜色进行比较。我已经尝试过在色彩空间上进行图像分割的解决方案,但我做不到。

我正在使用 Python“OpenCV”。

I want to make program like:

given_color = Blue (Color Values)
if Blue == Color_values_detected_from_image:
    print("Blue Color is present at your given area")
else:
    print("Given Color Not Found")

你能告诉我应该从哪里开始吗?

我希望如果我在图像的某个区域给出矩形坐标,那么它应该与我给定的颜色值进行比较。

【问题讨论】:

    标签: python-3.x opencv image-processing color-detection


    【解决方案1】:

    这可以通过简单的逐像素比较和 NumPy 的 all 方法来完成。

    让我们看看下面的代码:

    import cv2
    import numpy as np
    
    # Read input image
    img = cv2.imread('images/colors.png', cv2.IMREAD_COLOR)
    cv2.imshow('img', img)
    
    # Region of interest (x1, x2, y1, y2)
    roi = (200, 700, 0, 100)
    imgRoi = img[roi[2]:roi[3], roi[0]:roi[1]]
    cv2.imshow('imgRoi', imgRoi)
    
    # Color of interest [B, G, R]
    coi = [0, 255, 0]
    
    # Compare each pixel with color; logical AND over all colors (axis=2)
    cmp = np.all(imgRoi == coi, axis=2)
    
    # From here, do whatever you like with this information...
    
    # For example, show mask where color of interest was found
    out = np.zeros((imgRoi.shape[0], imgRoi.shape[1], 1), np.uint8)
    out[cmp] = 255
    cv2.imshow('out', out)
    
    cv2.waitKey(0)
    

    输入图像如下所示:

    感兴趣区域 (ROI) 如下所示:

    作为示例输出,下面是找到感兴趣颜色 #00ff00 的掩码:

    希望有帮助!

    附: Python/NumPy 大师们可能会建议一种更优雅的方式将(x1, y1)(x2, y2) 两点“翻译”为索引x1:x2y1:y2。现在,这个符号看起来很麻烦......

    【讨论】:

    • 它有点工作,但主要问题是我想获得交通信号的状态,然后我想用状态结果做另一个过程。另一个是如果颜色差异很小?就像各种色调的颜色或 ROI 包含不同的色调。
    • @AnantPatankar 不幸的是,您最初的问题有一个(非常)有限的问题陈述。 1)您可以将我的方法封装在一些返回一些布尔值的函数中,指示是否在 ROI 中找到了颜色。这项工作留给你。 2)检查OpenCV的inRange方法。方法基本相同。以后在 StackOverflow 上提问的时候,请把你要解决的实际问题表述清楚,而不是只写有限的一部分,以防止半生不熟的答案。
    猜你喜欢
    • 2018-01-20
    • 1970-01-01
    • 2022-06-18
    • 1970-01-01
    • 2019-11-10
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    相关资源
    最近更新 更多