用python写一个能够把车牌水平、垂直矫正后,恢复成一个归一化的标准的车牌
时间: 2023-11-28 19:49:48 浏览: 19
要实现这个功能,需要用到图像处理库OpenCV和Python的NumPy库。步骤如下:
1. 读入车牌图像。
```python
import cv2
import numpy as np
img = cv2.imread('car_plate.jpg')
```
2. 将图像转为灰度图,并进行二值化处理。
```python
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
```
3. 找到车牌轮廓。
```python
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contour = max(contours, key=cv2.contourArea)
```
4. 进行车牌矫正。
```python
rect = cv2.minAreaRect(contour)
angle = rect[-1]
if angle < -45:
angle += 90
h, w = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
```
5. 对矫正后的车牌进行裁剪和归一化。
```python
plate_width, plate_height = 136, 36
plate_img = cv2.getRectSubPix(rotated, (int(rect[1][0]), int(rect[1][1])), center)
plate_img = cv2.cvtColor(plate_img, cv2.COLOR_BGR2GRAY)
_, plate_img = cv2.threshold(plate_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
plate_img = cv2.resize(plate_img, (plate_width, plate_height))
```
完整代码如下:
```python
import cv2
import numpy as np
img = cv2.imread('car_plate.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contour = max(contours, key=cv2.contourArea)
rect = cv2.minAreaRect(contour)
angle = rect[-1]
if angle < -45:
angle += 90
h, w = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
plate_width, plate_height = 136, 36
plate_img = cv2.getRectSubPix(rotated, (int(rect[1][0]), int(rect[1][1])), center)
plate_img = cv2.cvtColor(plate_img, cv2.COLOR_BGR2GRAY)
_, plate_img = cv2.threshold(plate_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
plate_img = cv2.resize(plate_img, (plate_width, plate_height))
cv2.imshow('Plate Image', plate_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,'car_plate.jpg'是待处理的车牌图像文件名。运行代码后,会显示出矫正后的车牌图像。