python - 相机捕获蓝色时如何打印文本?

标签 python opencv numpy

我正在使用opencv和python在脚本捕获特定颜色时打印文本的脚本。我尝试使用if语句,但失败。

这是我的代码:

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])
    result = lower_blue + upper_blue

    # 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)

    if result.any() == True:
       print 'I can see blue color'

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

最佳答案

我制定了一个适合我的环境的解决方案。我正在使用Python 2.7和OpenCV 2.4.6。您可能需要修改blue_threshold值以适合您的需求。

import cv2
import numpy as np

cap = cv2.VideoCapture(0)
blue_threshold = 1000000  # This value you could change for what works best

while True:

    # 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)
    count = mask.sum()

    if count > blue_threshold:
       print 'I can see blue color'


    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

关于python - 相机捕获蓝色时如何打印文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31476793/

相关文章:

python - NumPy - 从另一个二维数组中选择子矩阵

python - numpy从上到下排序

python - Python 中的神经网络,不使用任何现成的库......即从第一原则开始......帮助!

python - 如何使用笔记本中的组合框以 python 形式进行计算?

python - 如何在视频上叠加

opencv - cvLoadImage 适用于字符串常量但不适用于 c_str()

python - 为函数提供多个参数

python - 将类型为 "object"的数据帧列转换为 set()

图像配准(非刚性\非线性)

Python:替换numpy数组的每第5个值