基于opencv图像处理对交通路口的红绿灯进行颜色检测

1.视频读取首先把视频读取进来 , 因为我测试的视频是4k的所以我用resize调整了一下视频的分辨大小
cap = cv2.VideoCapture('video/小路口.mp4')while True:ret,frame = cap.read()if ret == False:breakframe = cv2.resize(frame,(1920,1080))cv2.imshow('frame',frame)c = cv2.waitKey(10)if c==27:breakimshow()(如下图所示)
基于opencv图像处理对交通路口的红绿灯进行颜色检测文章插图
2.截取roi区域截取roi的区域 , 也就是说 , 为了避免多余的干扰因素我们要把红绿灯的位置给截取出来(如下图所示)
基于opencv图像处理对交通路口的红绿灯进行颜色检测文章插图
截取后的roi(如下图所示)
基于opencv图像处理对交通路口的红绿灯进行颜色检测文章插图
3.转换hsv颜色空间HSV颜色分量范围(详细参考原文链接)一般对颜色空间的图像进行有效处理都是在HSV空间进行的 , 然后对于基本色中对应的HSV分量需要给定一个严格的范围 , 下面是通过实验计算的模糊范围(准确的范围在网上都没有给出) 。
H: 0— 180
S: 0— 255
V: 0— 255
此处把部分红色归为紫色范围(如下图所示):
基于opencv图像处理对交通路口的红绿灯进行颜色检测文章插图
上面是已给好特定的颜色值 , 如果你的颜色效果不佳 , 可以通过python代码来对min和max值的微调 , 用opencv中的api来获取你所需理想的颜色 , 可以复制以下代码来进行颜色的调整 。 1.首先你要截取roi区域的一张图片2.读取这张图然后调整颜色值
颜色调整代码如下:(详细参考视频教程链接)
import cv2import numpy as npdef empty(a):passdef 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]*rowshor_con = [imageBlank]*rowsfor 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 = horreturn 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)运行代码后调整的结果(如下图所示) , 很明显可以看到绿色已经被获取到 。
基于opencv图像处理对交通路口的红绿灯进行颜色检测文章插图
4.二值图像颜色判定因为图像是二值的图像 , 所以如果图像出现白点 , 也就是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')5.颜色结果画在图像上用矩形框来框选出红绿灯区域
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文本信息6.完整代码import cv2import numpy as npcap = cv2.VideoCapture('video/小路口.mp4')while True:ret,frame = cap.read()if ret == False:breakframe = cv2.resize(frame,(1920,1080))#截取roi区域roiColor = frame[50:90,950:1100]#转换hsv颜色空间hsv = cv2.cvtColor(roiColor,cv2.COLOR_BGR2HSV)#redlower_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)#greenlower_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最大值255red_color = np.max(red_blur)green_color = np.max(green_blur)#在red_color中判断二值图像如果数值等于255 , 那么就判定为redif red_color == 255:print('red')# 。。。 这是我经常会混淆的坐标 。。。就列举出来记一下 。。。#yy+h xx+w#frame[50:90,950:1100]#xyx+wy+hcv2.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 , 那么就判定为greenelif 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