import cv2
import numpy as np
from paddleocr import PaddleOCR
def show_image(desc, image):
cv2.imshow(desc, image)
cv2.waitKey(0)
cv2.destroyAllWindows()
def reg_area_color(image):
"""找到原图像最多的颜色,当该颜色为红色、蓝色或绿色时返回该颜色的名称"""
kernel = np.ones((35, 35), np.uint8)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# 图像开运算去噪
Open = cv2.morphologyEx(hsv, cv2.MORPH_OPEN, kernel)
# 统计H通道直方图
hist = cv2.calcHist([Open], [0], None, [180], [0, 180])
hist_max = np.where(hist == np.max(hist))
h_value = hist_max[0][0] # 提取出现频率最高的H值
# 颜色范围判断
if 0 < h_value < 10: # 红色区域
res_color = 'red'
elif 100 < h_value < 124: # 蓝色区域
res_color = 'blue'
elif 35 <= h_value <= 85: # 新增绿色区域
res_color = 'green'
else:
res_color = 'unknow'
return res_color
img = cv2.imread('D:/wk/pythonProject/456.png')
# 调整图片大小
img = cv2.resize(img, (1024, 768))
# 灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
show_image('gray', gray)
# 双边滤波
blf = cv2.bilateralFilter(gray, 13, 15, 15)
show_image('bilateralFilter', blf)
# 边缘检测
edged = cv2.Canny(blf, 30, 200)
show_image('canny', edged)
# 寻找轮廓(图像矩阵,输出模式,近似方法)
contours, _ = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 根据区域大小排序取前十
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:10]
screenCnt = None
# 遍历轮廓,找到车牌轮廓
for c in contours:
if cv2.contourArea(c) > 1024 * 768 * 0.05:
continue
# 计算轮廓周长(轮廓,是否闭合)
peri = cv2.arcLength(c, True)
# 折线化(轮廓,阈值(越小越接近曲线),是否闭合)返回折线顶点坐标
approx = cv2.approxPolyDP(c, 0.018 * peri, True)
# 获取四个顶点(即四边形, 左下/右下/右上/左上
if len(approx) == 4:
# [参数]左上角纵坐标:左下角纵坐标,左上角横坐标:右上角横坐标
crop_image = img[approx[3][0][1]:approx[0][0][1], approx[3][0][0]:approx[2][0][0]]
show_image('crop', crop_image)
screenCnt = approx
break
# 如果找到了四边形
if screenCnt is not None:
# 绘制轮廓到原图(仅用于显示)
cv2.drawContours(img, [screenCnt], -1, (0, 0, 255), 3)
show_image('contour', img)
"""遮罩处理"""
mask = np.zeros(gray.shape, np.uint8)
# 确保screenCnt是整数类型且形状正确
cv2.drawContours(mask, [screenCnt], 0, 255, -1)
mask_image = cv2.bitwise_and(img, img, mask=mask)
show_image('mask_image', mask_image)
else:
print("未找到符合条件的车牌轮廓!")
exit() # 提前退出避免后续错误
"""遮罩"""
# 创建一个灰度图一样大小的图像矩阵
mask = np.zeros(gray.shape, np.uint8)
# 将创建的图像矩阵的车牌区域画成白色
cv2.drawContours(mask, [screenCnt], 0, 255, -1, )
# 图像位运算进行遮罩
mask_image = cv2.bitwise_and(img, img, mask=mask)
show_image('mask_image', mask_image)
"""图像剪裁"""
# 获取车牌区域的所有坐标点
(x, y) = np.where(mask == 255)
# 获取底部顶点坐标
(topx, topy) = (np.min(x), np.min(y))
# 获取底部坐标
(bottomx, bottomy,) = (np.max(x), np.max(y))
# 剪裁
cropped = gray[topx:bottomx, topy:bottomy]
show_image('cropped', cropped)
"""OCR识别"""
# 使用CPU预加载,不用GPU
ocr = PaddleOCR(use_angle_cls=True, use_gpu=False, ocr_version='PP-OCRv3')
text = ocr.ocr(cropped, cls=True)
for t in text:
print(t[0][1]) 运行代码后显示未找到符合条件的车牌轮廓! 我该怎么办
最新发布