前两天看了几篇图像处理方面的文章,然后了解到车牌识别,是一个典型的目标提取的处理过程。然后就按照一般处理方法,进行了一些小的实验,效果不是很好,纯属好奇。仅供参考。
import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
def show_pic(path):
#读入图
initial_img = cv2.imread(path) #(600, 800, 3) 行,列,通道数
#initial_RGB = cv2.cvtColor(initial_img,cv2.COLOR_BGR2RGB)
#灰度处理图像
Gray_img = cv2.cvtColor(initial_img,cv2.COLOR_BGR2GRAY)
#高斯去燥
Gaussian = cv2.GaussianBlur(Gray_img, (5,5), 0, 0, cv2.BORDER_DEFAULT)
#中值滤波
Median = cv2.medianBlur(Gaussian, 5)
#双边滤波
#Test = cv2.bilateralFilter(Gray_img,9,25,25)
'''
#sobel算子 轮廓
# Sobel算子 XY方向求梯度
x = cv2.Sobel(Median, cv2.CV_8U, 1, 0, ksize = 3) #X方向
y = cv2.Sobel(Median, cv2.CV_8U, 0, 1, ksize = 3) #Y方向
absX = cv2.convertScaleAbs(x) # 转回uint8
absY = cv2.convertScaleAbs(y)
Sobel = cv2.addWeighted(absX, 0.5, absY, 0.5,0)
'''
#Canny边缘处理
Canny = cv2.Canny(Median, 50, 200)
#Otsu大津算法自适应阈值二值化
ret, Binary = cv2.threshold(Canny,170, 255, cv2.THRESH_OTSU|cv2.THRESH_BINARY)
#建立一个椭圆核函数,闭操作
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (25, 25))
#执行图像形态学, 细节直接查文档,很简单
closed = cv2.morphologyEx(Binary, cv2.MORPH_CLOSE, kernel)
closed = cv2.erode(closed, None, iterations=4)
closed = cv2.dilate(closed, None, iterations=4)
#提取轮廓
contours,_ = cv2.findContours(closed.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#画出轮廓排序,cv2.contourArea 计算轮廓面积,将最大的那组轮廓挑出来
c = sorted(contours, key=cv2.contourArea, reverse=True)[0]
#compute the rotated bounding box of the largest contour
rect = cv2.minAreaRect(c) #画出轮廓的最小外接矩形
Box = np.int0(cv2.boxPoints(rect)) #获取最小外接矩形的4个顶点
#按照Box画出轮廓
Final_img = cv2.drawContours(initial_img.copy(),[Box], -1, (255, 255, 255), -1)
Xs = [i[0] for i in Box]
Ys = [i[1] for i in Box]
x1 = min(Xs)
x2 = max(Xs)
y1 = min(Ys)
y2 = max(Ys)
hight = y2 - y1
width = x2 - x1
crop_img = initial_img.copy()[y1:y1+hight, x1:x1+width]
#return crop_img
cv2.imshow("12",crop_img )
cv2.waitKey(0)
show_pic(path)
参考:
https://blog.csdn.net/Eastmount/article/details/81461679