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

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

所以我有以下代码,并在图像上显示颜色时工作正常。我知道它在原始图像上使用了一个遮罩,只显示在声明的边界中定义的颜色。所以基本上它不会“检测”颜色,而是覆盖范围内不包含的所有其他颜色。

用法: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

我尝试通过打印掩码和输出进行调试,但这些只返回零元组:

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

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

python opencv colors detection cv2
1个回答
1
投票

您可以将colorsboundaries组合成一个对象来迭代。无论如何,组合数据是一个好主意,因为下限/上限目前是重复的,一次在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()}")
© www.soinside.com 2019 - 2024. All rights reserved.