OpenCV-Python小应用(四):红绿灯检测

前言

  • 本文是个人使用OpenCV-Python的应用案例,由于水平有限,难免出现错漏,敬请批评改正。
  • 更多精彩内容,可点击进入
    OpenCV-Python小应用
    专栏或我的个人主页查看

前提条件

实验环境

  • Python 3.6.13 (面向对象的高级语言)
  • OpenCV 3.4.10(python第三方库)pip3 install opencv-python==3.4.10.37

红绿灯检测

在这里插入图片描述

import cv2
import numpy as np

img=cv2.imread("light3.png")

#=============指定红色值的范围=============
minRed = np.array([0, 127, 128]) # 红色阈值下界
maxRed = np.array([10, 255, 255]) # 红色阈值上界
#=============指定绿色值的范围=============
minGreen = np.array([50,100,20])
maxGreen = np.array([90,255,200])
# BGR -> HSV颜色空间
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# 确定目标区域
mask_red = cv2.inRange(img_hsv, minRed, maxRed) # 过滤出红色部分,获得红色的掩膜
mask_green = cv2.inRange(img_hsv, minGreen, maxGreen) # 获得绿色部分掩膜

# 查找轮廓
contours1, hierarchy1 = cv2.findContours(mask_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # 轮廓检测 红灯
contours2, hierarchy2 = cv2.findContours(mask_green, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # 轮廓检测 绿灯


# 检测红灯
for cnt in contours1:
    (x, y, w, h) = cv2.boundingRect(cnt) # 该函数返回矩阵四个点
    if w*h < 20*20: # 忽略20*20的框
        continue
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 255), 2) # 将检测到的颜色框起来
    cv2.putText(img, 'red_light', (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
# 检测绿灯
for cnt in contours2:
    (x, y, w, h) = cv2.boundingRect(cnt) # 该函数返回矩阵四个点
    if w*h < 20*20: # 忽略20*20的框
        continue
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # 将检测到的颜色框起来
    cv2.putText(img, 'green_light', (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.6,(0, 255, 0) , 2)

cv2.imshow('res', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述

参考文献

[1] https://opencv.org/
[2] 李立宗. OpenCV轻松入门:面向Python. 北京: 电子工业出版社,2019

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐