Python+Opencv简易车牌识别(一):基于HSV颜色空间的图像分割

注:这是一个非常简单的车牌识别demo

1.前言

首先看疗效:
原图:
在这里插入图片描述
输出:
在这里插入图片描述
代码:

import cv2
import numpy as np
image = cv2.imread(r'D:\car1.png')
hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower = np.array([110, 100, 150])
upper = np.array([125, 200, 255])
mask = cv2.inRange(hsv_img, lowerb=lower, upperb=upper)
kernel = np.ones((5,5), np.uint8)
mask = cv2.dilate(mask, kernel, iterations=10)
contours, hier = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    x, y, w, h = cv2.boundingRect(c)
    if w < 2*h:
        continue
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) 
cv2.imshow("image", image)
cv2.waitKey(0)

2.分析

2.1.HSV颜色空间

HSV模型和RGB模型一样是用来表示表示颜色空间的,其中:

  • H(Hue):色调,即"颜色"
  • S(Saturation):饱和度,S=0表示只有灰度
  • V(Value):明度,表示色彩的明亮程度

根据经验,蓝色车牌的HSV范围空间在[110, 100, 150]到[125, 200, 255]这一范围内。

2.2 掩膜

基于上面的经验结论我们可以直接利用opencv中的inRange方法对图像进行mask处理:

import cv2
import numpy as np
image = cv2.imread(r'D:\car1.png')
#将图片从RGB色彩空间转换至HSV色彩空间
hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
#下界
lower = np.array([110, 100, 150])
#上界
upper = np.array([125, 200, 255])
#设置mask
mask = cv2.inRange(hsv_img, lowerb=lower, upperb=upper)
kernel = np.ones((5,5), np.uint8)
mask = cv2.dilate(mask, kernel, iterations=10)

画出来的掩膜是这样的(也就是原图中车牌的大致区域):
在这里插入图片描述

2.3.画框

最后给图片加上方框便可以完成识别了。

contours, hier = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    x, y, w, h = cv2.boundingRect(c)
    if w < 2*h:
        continue
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值