[英]Detecting color of ball using openCV from a live video feed
我試圖從網絡攝像頭中檢測出球的顏色。 我嘗試的顏色是紅色,綠色,藍色和黃色。 我寫了下面的代碼。 但是,即使沒有球,它也會顯示隨機檢測到的藍色球。 而且,當顯示綠色或紅色時,檢測到的藍色球會在兩者之間彈出。 請提出一些使其更准確的方法,以及如何添加黃色。
enter code here
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
lower_green = np.array([45,140,50])
upper_green = np.array([75,255,255])
lower_red = np.array([160,140,50])
upper_red = np.array([180,255,255])
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
foundred = False
while(True):
success,frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
hsv = cv2.medianBlur(hsv,5)
imgThreshHighred = cv2.inRange(hsv, lower_red, upper_red)
imgThreshHighgreen = cv2.inRange(hsv, lower_green, upper_green)
imgThreshHighblue = cv2.inRange(hsv, lower_blue, upper_blue)
circlesred = cv2.HoughCircles(imgThreshHighred,cv2.HOUGH_GRADIENT,1,20,param1=50,param2=30,minRadius=0,maxRadius=0)
circlesblue = cv2.HoughCircles(imgThreshHighblue,cv2.HOUGH_GRADIENT,1,20,param1=50,param2=30,minRadius=0,maxRadius=0)
circlesgreen = cv2.HoughCircles(imgThreshHighgreen,cv2.HOUGH_GRADIENT,1,20,param1=50,param2=30,minRadius=0,maxRadius=0)
if circlesred is not None:
print "found red"
# print circlesred
if circlesgreen is not None:
print "found green"
# print circlesgreen
if circlesblue is not None:
print "found blue"
# print circlesblue
else:
print "no ball"
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
您正在觀察假陽性,並且正如Flamelite指出的,它們是由圖像中位於目標HSV范圍內的其他區域引起的。 使用您當前的方法,這很正常。 基於色彩區域檢測的檢測幾乎可以肯定會在自然圖像中產生誤報。 要減少或消除誤報,您有兩種策略。
1.使用更具體的顏色模型。 您可以按照Flamelite建議的使用更窄的HSV范圍來執行此操作,也可以使用OpenCV的EM
類高斯混合模型方法為每個球訓練一個高斯模型。 這可以用於細分,並將替換您的3行代碼inRange
。 在這兩種方法中,您都必須注意訓練圖像與測試圖像相匹配(特別是,照明類似,並且訓練圖像中表示的自動白平衡(如果激活)會產生顏色變化)。
2.使用其他功能/信息。 如果仍然留下誤報,則需要使用顏色以外的屬性消除誤報。 例如,視頻中球的半徑大約恆定嗎? 如果是這樣,您可以拒絕明顯太小或太大的區域。 這可能非常有效。 背景不動嗎? 如果是這樣,您可以嘗試使用OpenCV的背景減法來消除誤報。 您一次只看到一個球嗎? 如果是這樣,您可以使用例如每個區域上高斯色彩模型對數似然率的平均值來拒絕除最可能的“球形”區域以外的所有區域。
我猜想在圖像框中的某個點上一定有一些色度值在藍色范圍內的小成分,這就是為什么您將藍色表示為假陽性。 這是我的建議:
所有這三種像素的最大值將為您提供真實的球色。
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.