Embedded_game/chepai/车牌倾斜.py

53 lines
1.2 KiB
Python
Raw Normal View History

2025-01-02 12:48:11 +08:00
# -*- coding: utf-8 -*-
# @Time : 2024/11/10 09:08
# @Author : len
# @File : 车牌倾斜.py
# @Software: PyCharm
# @Comment :
import cv2
import numpy as np
# 读取图片
image = cv2.imread('./img/img_1.png')
# 转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 使用边缘检测
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
# 找到轮廓
contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 找到面积最大的矩形轮廓,假设为车牌
plate_contour = max(contours, key=cv2.contourArea)
# 获取最小外接矩形
rect = cv2.minAreaRect(plate_contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
# 透视变换准备
width, height = int(rect[1][0]), int(rect[1][1])
# 确保宽度大于高度
if width < height:
width, height = height, width
# 定义目标点
dst_points = np.array([[0, 0], [width-1, 0], [width-1, height-1], [0, height-1]], dtype="float32")
src_points = np.array(box, dtype="float32")
# 计算透视变换矩阵
M = cv2.getPerspectiveTransform(src_points, dst_points)
# 透视变换
warped = cv2.warpPerspective(image, M, (width, height))
# 显示结果
cv2.imshow("Original", image)
cv2.imshow("Corrected Plate", warped)
cv2.waitKey(0)
cv2.destroyAllWindows()