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

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

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FriendshipT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值