Open cv2 识别红绿灯

1. 导入相关库

import cv2
import numpy as np

2. 导入视频

cap = cv2.VideoCapture("红绿灯.mp4")

3. 修改视频尺寸

frame = cv2.resize(frame, (1620, 900))

4. 转换hsv颜色空间

hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

5. 红灯

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) #中值滤波

6.  绿灯

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) #中值滤波

7. 二值图像颜色的判定(因为图像是二值的图像,所以如果图像出现白点,也就是255,那么就取他的max最大值255,在red_color中判断二值图像如果数值等于255,那么就判定为红,在green_color中判断二值图像如果数值等于255,那么就判定为绿。)

red_color = np.max(red_blur)
green_color = np.max(green_blur)
if red_color == 255:
    print('红')
    cv2.rectangle(frame, (660, 420), (400, 300), (0, 0, 255), 2)  # 按坐标画出矩形框
    cv2.putText(frame, "red", (500, 280), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 2)
elif green_color == 255:
    print('绿')
    cv2.rectangle(frame, (660, 420), (400, 300), (0, 255, 0), 2)
    cv2.putText(frame, "green", (500, 280), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)

8. 将结果展示

cv2.imshow('frame',frame)
red_blur = cv2.resize(red_blur,(200,150))
green_blur = cv2.resize(green_blur,(200,150))
cv2.imshow('red',red_blur)
cv2.imshow('green',green_blur)
c = cv2.waitKey(1)

最终展示结果为:

 

 

 

9. 完整代码:

#导库
import cv2
import numpy as np
cap = cv2.VideoCapture("红绿灯.mp4") #导入视频
while True:
    ret,frame = cap.read()
    if ret == False:
        break
    frame = cv2.resize(frame, (1620, 900)) #修改视频尺寸
    img = frame[100:500,300:800]
    hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) #转换hsv颜色空间
    #红灯
    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)
    #绿灯
    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)
    red_color = np.max(red_blur)
    green_color = np.max(green_blur)   
    if red_color == 255:
        print('红')
        cv2.rectangle(frame, (660, 420), (400, 300), (0, 0, 255), 2)  # 按坐标画出矩形框
        cv2.putText(frame, "red", (500, 280), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 2) #显示文本信息
    elif green_color == 255:
        print('绿')
        cv2.rectangle(frame, (660, 420), (400, 300), (0, 255, 0), 2)
        cv2.putText(frame, "green", (500, 280), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
    cv2.imshow('frame',frame)
    red_blur = cv2.resize(red_blur,(200,150))
    green_blur = cv2.resize(green_blur,(200,150))
    cv2.imshow('red',red_blur)
    cv2.imshow('green',green_blur)
    c = cv2.waitKey(1)
    if c==1:
        break

你可能感兴趣的:(python,opencv,numpy)