首先把視訊讀取進來,因為我測試的視訊是4k的所以我用resize調整了一下視訊的分辨大小
cap = cv2.VideoCapture('video/小路口.mp4')
while True:
ret,frame = cap.read()
if ret == False:
break
frame = cv2.resize(frame,(1920,1080))
cv2.imshow('frame',frame)
c = cv2.waitKey(10)
if c==27:
break
imshow()(如下圖所示)
擷取roi的區域,也就是說,為了避免多餘的干擾因素我們要把紅綠燈的位置給擷取出來(如下圖所示)
擷取後的roi(如下圖所示)
HSV顏色分量範圍(詳細參考原文連結)
一般對顏色空間的影象進行有效處理都是在HSV空間進行的,然後對於基本色中對應的HSV分量需要給定一個嚴格的範圍,下面是通過實驗計算的模糊範圍(準確的範圍在網上都沒有給出)。H: 0— 180
S: 0— 255
V: 0— 255
此處把部分紅色歸為紫色範圍(如下圖所示):
上面是已給好特定的顏色值,如果你的顏色效果不佳,可以通過python程式碼來對min和max值的微調,用opencv中的api來獲取你所需理想的顏色,可以複製以下程式碼來進行顏色的調整。
1.首先你要擷取roi區域的一張圖片
2.讀取這張圖然後調整顏色值
顏色調整程式碼如下:(詳細參考視訊教學連結)
import cv2
import numpy as np
def empty(a):
pass
def stackImages(scale,imgArray):
rows = len(imgArray)
cols = len(imgArray[0])
rowsAvailable = isinstance(imgArray[0], list)
width = imgArray[0][0].shape[1]
height = imgArray[0][0].shape[0]
if rowsAvailable:
for x in range ( 0, rows):
for y in range(0, cols):
if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:
imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
else:
imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)
imageBlank = np.zeros((height, width, 3), np.uint8)
hor = [imageBlank]*rows
hor_con = [imageBlank]*rows
for x in range(0, rows):
hor[x] = np.hstack(imgArray[x])
ver = np.vstack(hor)
else:
for x in range(0, rows):
if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
else:
imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)
if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
hor= np.hstack(imgArray)
ver = hor
return ver
#讀取的圖片路徑
path = './green.jpg'
cv2.namedWindow("TrackBars")
cv2.resizeWindow("TrackBars",640,240)
cv2.createTrackbar("Hue Min","TrackBars",0,179,empty)
cv2.createTrackbar("Hue Max","TrackBars",19,179,empty)
cv2.createTrackbar("Sat Min","TrackBars",110,255,empty)
cv2.createTrackbar("Sat Max","TrackBars",240,255,empty)
cv2.createTrackbar("Val Min","TrackBars",153,255,empty)
cv2.createTrackbar("Val Max","TrackBars",255,255,empty)
while True:
img = cv2.imread(path)
imgHSV = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
h_min = cv2.getTrackbarPos("Hue Min","TrackBars")
h_max = cv2.getTrackbarPos("Hue Max", "TrackBars")
s_min = cv2.getTrackbarPos("Sat Min", "TrackBars")
s_max = cv2.getTrackbarPos("Sat Max", "TrackBars")
v_min = cv2.getTrackbarPos("Val Min", "TrackBars")
v_max = cv2.getTrackbarPos("Val Max", "TrackBars")
print(h_min,h_max,s_min,s_max,v_min,v_max)
lower = np.array([h_min,s_min,v_min])
upper = np.array([h_max,s_max,v_max])
mask = cv2.inRange(imgHSV,lower,upper)
imgResult = cv2.bitwise_and(img,img,mask=mask)
imgStack = stackImages(0.6,([img,imgHSV],[mask,imgResult]))
cv2.imshow("Stacked Images", imgStack)
cv2.waitKey(1)
執行程式碼後調整的結果(如下圖所示),很明顯可以看到綠色已經被獲取到。
因為影象是二值的影象,所以如果影象出現白點,也就是255,那麼就取他的max最大值255,視訊幀的不斷變化然後遍歷每個顏色值
red_color = np.max(red_blur)
green_color = np.max(green_blur)
if red_color == 255:
print('red')
elif green_color == 255:
print('green')
用矩形框來框選出紅綠燈區域
cv2.rectangle(frame,(1020,50),(1060,90),(0,0,255),2) #按座標畫出矩形框
cv2.putText(frame, "red", (1020, 40), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255),2)#顯示red文字資訊
import cv2
import numpy as np
cap = cv2.VideoCapture('video/小路口.mp4')
while True:
ret,frame = cap.read()
if ret == False:
break
frame = cv2.resize(frame,(1920,1080))
#擷取roi區域
roiColor = frame[50:90,950:1100]
#轉換hsv顏色空間
hsv = cv2.cvtColor(roiColor,cv2.COLOR_BGR2HSV)
#red
lower_hsv_red = np.array([157,177,122])
upper_hsv_red = np.array([179,255,255])
mask_red = cv2.inRange(hsv,lowerb=lower_hsv_red,upperb=upper_hsv_red)
#中值濾波
red_blur = cv2.medianBlur(mask_red, 7)
#green
lower_hsv_green = np.array([49,79,137])
upper_hsv_green = np.array([90,255,255])
mask_green = cv2.inRange(hsv,lowerb=lower_hsv_green,upperb=upper_hsv_green)
#中值濾波
green_blur = cv2.medianBlur(mask_green, 7)
#因為影象是二值的影象,所以如果影象出現白點,也就是255,那麼就取他的max最大值255
red_color = np.max(red_blur)
green_color = np.max(green_blur)
#在red_color中判斷二值影象如果數值等於255,那麼就判定為red
if red_color == 255:
print('red')
#。。。這是我經常會混淆的座標。。。 就列舉出來記一下。。。
# y y+h x x+w
#frame[50:90,950:1100]
# x y x+w y+h
cv2.rectangle(frame,(1020,50),(1060,90),(0,0,255),2) #按座標畫出矩形框
cv2.putText(frame, "red", (1020, 40), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255),2)#顯示red文字資訊
#在green_color中判斷二值影象如果數值等於255,那麼就判定為green
elif green_color == 255:
print('green')
cv2.rectangle(frame,(1020,50),(1060,90),(0,255,0),2)
cv2.putText(frame, "green", (1020, 40), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0),2)
cv2.imshow('frame',frame)
red_blur = cv2.resize(red_blur,(300,200))
green_blur = cv2.resize(green_blur,(300,200))
cv2.imshow('red_window',red_blur)
cv2.imshow('green_window',green_blur)
c = cv2.waitKey(10)
if c==27:
break
檢測紅燈的效果(如下圖所示)
檢測綠燈的效果(如下圖所示)
最後!!!
第一次接觸opencv!所以請各位視覺領域的大佬們勿噴我這個小菜雞!(/狗頭)
程式碼量非常少,無泛化能力,很low的一種做法。。。不過對於小白的我來說學習hsv顏色空間還是很有幫助滴!幹就完了!奧利給!