OpenCV - 检测颜色范围并在控制台上显示

OpenCV - detecting color ranges and display on console

所以我有以下代码并且在图像上显示颜色时工作正常。我知道它在原始图像上使用了一个蒙版,并且只显示在声明的边界中定义的颜色。所以基本上它没有 "detect" 颜色,而是涵盖了不在范围内的所有其他内容。

用法:python code.py

您可以找到示例图像 here

代码:

import numpy as np
import cv2
import sys

image = cv2.imread(sys.argv[1])


colors = {
    "red_lower" : "[  0   0 255]",
    "red_upper" : "[  0   0 127]",
    "blue_lower" : "[255  38   0]",
    "blue_upper" : "[255  38   0]",
    "yellow_lower" : "[  0 216 255]",
    "yellow_upper" : "[  0 216 255]",
    "gray_lower" : "[160 160 160]",
    "gray_upper" : "[160 160 160]"
}

boundaries = [
    ([0, 0, 255], [127, 0, 255]), #red
    ([255, 38, 0], [255, 38, 0]), #blue
    ([0, 216, 255], [0, 216, 255]), #yellow
    ([160, 160, 160], [160, 160, 160]) #gray
]

# loop over the boundaries
for (lower, upper) in boundaries:

    # create NumPy arrays from the boundaries
    lower = np.array(lower, dtype = np.uint8)
    upper = np.array(upper, dtype = np.uint8)

    # find the colors within the specified boundaries and apply the mask
    mask = cv2.inRange(image, lower, upper)
    output = cv2.bitwise_and(image, image, mask = mask)

    # show the images
    cv2.imshow("Climbing Holds", np.hstack([image, output]))

    cv2.waitKey(0)

我试图在匹配其中一个边界时通过 If 语句在控制台上捕获颜色。如果我直接与我的颜色字典进行比较,将无法按预期工作,因为所有边界都经过循环。

If 语句示例:

if str(lower) == colors["red_lower"]:
    print "red"
elif str(upper) == colors["red_upper"]:
    print "dark red"
elif str(lower) == colors["blue_lower"]:
    print "blue"
elif str(lower) == colors["yellow_lower"]:
    print "yellow"
elif str(lower) == colors["gray_lower"]:
    print "gray

我尝试通过打印掩码和输出来调试,但是这些 return 只有零元组:

 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]]

有谁知道如何return掩码匹配?是否可以使用 cv2.imshow 或 cv2.read?

您可以将 colorsboundaries 合并到一个对象中进行迭代。无论如何,合并数据是一个好主意,因为 lower/upper 边界当前是重复的,一次在 boundaries 中,一次作为字符串在 colors 值中。这种重复不是很好,因为它会导致细微的错误。有些值似乎已经不同步,因此将它们放在一个地方不太容易出错。

color_boundaries = {
    "red":    ([0,   0,   255], [127, 0,   255]),
    "blue":   ([255, 38,  0],   [255, 38,  0]),
    "yellow": ([0,   216, 255], [0,   216, 255]),
    "gray":   ([160, 160, 160], [160, 160, 160])
}

for color_name, (lower, upper) in color_boundaries.items():
    # create NumPy arrays from the boundaries
    lower = np.array(lower, dtype = np.uint8)
    upper = np.array(upper, dtype = np.uint8)

    # find the colors within the specified boundaries and apply the mask
    mask = cv2.inRange(image, lower, upper)
    output = cv2.bitwise_and(image, image, mask = mask)

    if mask.any():
        print(f"{color_name}: {mask.sum()}")