【发布时间】:2019-02-04 14:49:33
【问题描述】:
所以我有以下代码,并且在图像上显示颜色时可以正常工作。我知道它在原始图像上使用蒙版,并且只显示在声明的边界中定义的颜色。所以基本上它不会“检测”颜色,而是覆盖范围之外的所有其他内容。
用法: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