如何在 OpenCV Python 中检测红色?

时间:2022-11-19
本文介绍了如何在 OpenCV Python 中检测红色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试检测从我的网络摄像头拍摄的视频中的红色.下面给出的以下代码示例取自 OpenCV 文档.代码如下:

I am trying to detect red color from the video that's being taken from my webcam. The following code example given below is taken from OpenCV Documentation. The code is given below:

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):

    # Take each frame
    _, frame = cap.read()

    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
    lower_blue = np.array([110,50,50])
    upper_blue = np.array([130,255,255])

    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

lower_blue = np.array([110,50,50]) 具有下限 Blue HSV 值,行 upper_blue = np.array([130,255,255]) 具有更高范围的蓝色 HSV 值.我在互联网上查找了红色的上限值和下限值,但找不到.如果有人能说出 OpenCV 的红色 HSV 值(OpenCV H 值范围为 0 - 179),那将非常有帮助.非常感谢您的帮助(提前).

The line lower_blue = np.array([110,50,50]) has the lower range Blue HSV value and the line upper_blue = np.array([130,255,255]) has the higher range Blue HSV value. I have looked for the upper value and lower value of Red color on internet but I couldn't find it. It would be very helpful if anyone could tell the HSV value of Red for OpenCV (OpenCV H value ranges from 0 - 179). Thanks a lot for help (In Advance).

我也尝试过运行以下命令来查找 Red 的范围,但我可能无法选择合适的值.我试过的是这个(红色):

I have also tried running the following to find the range of Red but I was unable to pick proper value maybe. What I tried was this(for red):

>>> green = np.uint8([[[0,255,0 ]]])
>>> hsv_green = cv2.cvtColor(green,cv2.COLOR_BGR2HSV)
>>> print hsv_green
[[[ 60 255 255]]]

这也取自 OpenCV 文档.请告诉我或帮我找到 OpenCV 的 RED COLOR 范围.

This was also taken from OpenCV documentation. Please tell me or help me find the RANGE of RED COLOR for OpenCV.

推荐答案

对 red 运行相同的代码似乎可行:

Running the same code for red seems to work:

>>> red = numpy.uint8([[[0,0,255]]])
>>> hsv_red = cv2.cvtColor(red,cv2.COLOR_BGR2HSV)
>>> print(hsv_red)
[[[  0 255 255]]]

然后您可以尝试不同颜色的偏红.请注意,红色范围包括略大于 0 的数字和略小于 179 的数字(例如 red = numpy.uint8([[[0,31,255]]]) 导致 [[[ 4 255 255]]]red = numpy.uint8([[[31,0,255]]]) 导致 [[[176 255 255]]]].

And then you can try different colors that appear reddish. Beware that the red range includes both numbers slightly greater than 0 and numbers slightly smaller than 179 (e.g. red = numpy.uint8([[[0,31,255]]]) results in [[[ 4 255 255]]] whereas red = numpy.uint8([[[31,0,255]]]) results in [[[176 255 255]]].

这篇关于如何在 OpenCV Python 中检测红色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!