簡體   English   中英

OpenCv Python 顏色檢測

[英]OpenCv Python Color Detection

我正在嘗試在 python 中使用 opencv 跟蹤紅色對象。 這是我到目前為止的代碼:

#Identify red objects in an image

#import OpenCV
import cv2
#Import numpy
import numpy as np

#open webcam
imgcap=cv2.VideoCapture(0)

while(1):

    #view the image from the webcam
    _, frame=imgcap.read()
    #convert the image to HSV
    hsv=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    #lower threshold for red
    lower_red=np.array([0, 100, 75])
    #upper threshold for red
    upper_red=np.array([5, 76, 100])

    mask=cv2.inRange(hsv, lower_red, upper_red)

當我運行它時,出現的錯誤如下:

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       cv::inRange, file ..\..\..\opencv-2.4.12\modules\core\src\arithm.cpp, line 2703
Traceback (most recent call last):
  File "red.py", line 23, in <module>
    mask=cv2.inRange(hsv, lower_red, upper_red)
cv2.error: ..\..\..\opencv-2.4.12\modules\core\src\arithm.cpp:2703: error: (-209) The lower bounary is neither an array of the same size and same type as src, nor a scalar in function cv::inRange

有人可以告訴我我做錯了什么嗎? 我試過了

lower_red=np.array([0, 100, 75], dtype=np.uint8) 

同樣,但這也不起作用。

我猜錯誤在hsv=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) ,根據變量命名我假設您想要一個 HSV 圖像,但您錯誤地使用cv2.COLOR_BGR2GRAY代替cv2.COLOR_BGR2HSV

由於cv2.COLOR_BGR2GRAY將圖像轉換為灰度並返回單通道圖像,因此應用mask=cv2.inRange(hsv, lower_red, upper_red)其中hsv是單通道圖像(同時使用cv2.COLOR_BGR2GRAY )和lower_redupper_red都有 3導致錯誤的元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM