本文介绍了使用opencv python进行颜色检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行在python中使用opencv编写的脚本,该脚本使用网络摄像头跟踪有色对象(此处的对象为蓝色),opencv的文档中也提到了此处

I am trying to run a script written using opencv in python which uses webcam to track colored objects (here the object is blue colored), which is also mentioned in opencv's documentation here

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

但是此代码会产生错误:

But this code produces error :

OpenCV Error: Sizes of input arguments do not match (The lower bounary is neither an      array of the same size and same type as src, nor a scalar) in inRange, file     /build/buildd/opencv-2.4.2+dfsg/modules/core/src/arithm.cpp, line 2527
Traceback (most recent call last):
File "blue.py", line 19, in <module>
mask = cv2.inRange(hsv, lower_blue, upper_blue)
cv2.error: /build/buildd/opencv-2.4.2+dfsg/modules/core/src/arithm.cpp:2527: error: (     (-209) The lower bounary is neither an array of the same size and same type as src, nor a scalar in function inRange

我已经尝试了相关的stackoverflow问题中提供的解决方案,但是没有一个有帮助.代码有什么问题?为什么会出现此错误?

I've tried solutions provided in related stackoverflow questions, but none of them helped.What is the problem with the code ? why this error arises ?

我正在使用opencv 2.4.2& ubuntu上的python 2.7

I'm using opencv 2.4.2 & python 2.7 on ubuntu

推荐答案

HSV中蓝色的范围应为:

The range of blue color in HSV should be given as :

lower_blue = np.array([110, 50, 50], dtype=np.uint8)
upper_blue = np.array([130,255,255], dtype=np.uint8)

这篇关于使用opencv python进行颜色检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:12