【发布时间】:2019-12-25 05:54:05
【问题描述】:
我在 python 中编写了一个代码来检测 OpenCV 中的红色。我得到了正确的输出,但我想在代码中给用户输入来检测特定的颜色。例如:如果我将蓝色作为用户输入,它应该在输出上只显示蓝色。我还想添加一些属性作为输出,例如检测到该对象的时间和实时视频的位置。我是python和opencv的新手,如果我能得到一些指导会很棒。
我现有的代码如下:
import cv2
import numpy as np
# Capture the input frame from webcam
def get_frame(cap, scaling_factor):
# Capture the frame from video capture object
ret, frame = cap.read()
# Resize the input frame
frame = cv2.resize(frame, None, fx=scaling_factor,
fy=scaling_factor, interpolation=cv2.INTER_AREA)
return frame
if __name__=='__main__':
cap = cv2.VideoCapture(0)
scaling_factor = 0.5
# Iterate until the user presses ESC key
while True:
frame = get_frame(cap, scaling_factor)
# Convert the HSV colorspace
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Define 'blue' range in HSV colorspace
lower = np.array([60,100,100])
upper = np.array([180,255,255])
# Threshold the HSV image to get only blue color
mask = cv2.inRange(hsv, lower, upper)
# Bitwise-AND mask and original image
res = cv2.bitwise_and(frame, frame, mask=mask)
res = cv2.medianBlur(res, 5)
cv2.imshow('Original image', frame)
cv2.imshow('Color Detector', res)
# Check if the user pressed ESC key
c = cv2.waitKey(5)
if c == 27:
break
cv2.destroyAllWindows()
【问题讨论】:
-
看看这个链接data-flair.training/blogs/project-in-python-colour-detection/…可以使用这里使用的数据集。对于任何颜色,您将从数据集中获取它的 RGB 值并转换为 HSV 并检查特定范围。
-
这个项目没有我正在寻找的答案。我需要为用户提供特定颜色的输入,并且只能在输出中检测到该颜色。我不知道怎么写那个函数。
-
使用这个HSV color thresholder script to isolate the desired color range。为每种颜色定义颜色 HSV 范围后,您可以将它们设置为预定义范围。当用户选择颜色时,您将上下范围切换到所选范围
-
@nathancy 您提到的脚本很有帮助。谢谢你。是否有任何脚本可以计算对象在我的实时视频中出现的时间。例如:最初视频中没有人,一旦有人进来,我必须计算那个物体的时间,直到它从视频中消失。
标签: python opencv color-detection