python+opencv 车牌位置获取

  • Post author:
  • Post category:python


目前使用环境:

python -3.9-64

opencv-python 4.6.0.66

opencv-contrib-python 4.6.0.66

matplotlib 3.5.3

import cv2 as cv
from matplotlib import pyplot as plt

#显示图片
def cv_show(name,img):
    cv.imread(name,img)
    cv.waitKey()
    cv.destroyAllWindows()

#plt 显示色彩图片
def plt_showCs(img):
    b, g, r = cv.split(img)
    img = cv.merge([r,g,b])
    plt.imshow(img)
    plt.show()

# plt 显示灰度图片
def plt_showHz(img):
    plt.imshow(img,cmap='gray')
    plt.show()

# 加载图片
url='D:/images/carp7.jpg'
rewImage = cv.imread(url)
plt_showCs(rewImage)

# 高斯去噪
gasImg = cv.GaussianBlur(rewImage, (3, 3), 0)
plt_showHz(gasImg)

# 灰度处理
gray_Img = cv.cvtColor(gasImg, cv.COLOR_BGR2GRAY) # 传入 去高斯后图片, 二值化处理
plt_showHz(gray_Img)

# soble算子边缘检测(做了y方向检测)
Soble_x =  cv.Sobel(gray_Img, cv.CV_16S, 1, 0)
absX = cv.convertScaleAbs(Soble_x) #转回uint8
plt_showHz(absX)

# 自适应阈值处理
ret, image = cv.threshold(absX, 0 , 255, cv.THRESH_OTSU) # 黑白两个值
plt_showHz(image)

# 闭运算, 是白色部分分拣成整体  膨胀 腐蚀
KernelX = cv.getStructuringElement(cv.MORPH_RECT, (17, 5)) # 横向粒度
print(KernelX)
image = cv.morphologyEx(image, cv.MORPH_CLOSE, KernelX, iterations=3)
plt_showHz(image)

# 去除一些白点
KernelX = cv.getStructuringElement(cv.MORPH_RECT, (20, 1))
KernelY = cv.getStructuringElement(cv.MORPH_RECT, (1, 19)) # MORPH_RECT 矩形
# 膨胀, 腐蚀
image = cv.dilate(image, KernelX)
image = cv.erode(image, KernelX)
# 腐蚀 膨胀
image = cv.erode(image, KernelY)
image = cv.dilate(image, KernelY)
plt_showHz(image)

#中值滤波去除噪点
image = cv.medianBlur(image, 15)
plt_showHz(image)

#轮廓检测
# RETR_EXTERNAL 外轮廓
# CHAIN_APPROX_SIMPLE 压缩水平方向,垂直,角度方向的元素 保留该方向的终点坐标
contours, hierarchy = cv.findContours(image, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
imagel = rewImage.copy()
cv.drawContours(imagel, contours, -1, (0, 255, 0), 2)
plt_showCs(imagel)

#筛选出车牌位置轮廓
# 车牌的长宽高比值  3~4 :1
for item in contours:
    rect = cv.boundingRect(item)
    print(rect)
    x = rect[0]
    y = rect[1]
    w = rect[2]
    h = rect[3]

    if (w> (h*3)) and (w < (h*4)):
        carP = rewImage[y: y+h, x: x+w]
        plt_showCs(carP)
        cv.imwrite('D:/images/cp/tqcp7.jpg', carP)
        print('提取成功')



版权声明:本文为weixin_43494908原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。