opencv 进行车牌检测,图片自选,并对检测的车牌进行图像分割车牌检测结果保存按钮,车牌图像分割按钮,退出按钮在GUI界面上显示代码
时间: 2024-04-05 14:35:57 浏览: 69
下面是一个基于Python和OpenCV的GUI程序,可以进行车牌检测、图像分割、结果保存等操作。请注意,车牌检测算法需要根据具体情况进行优化。
```python
import cv2
import numpy as np
import tkinter as tk
from tkinter import filedialog
class App:
def __init__(self, master):
self.master = master
master.title("车牌检测")
# 创建GUI控件
self.label = tk.Label(master, text="请在下方选择图片")
self.label.pack()
self.button1 = tk.Button(master, text="选择图片", command=self.load_image)
self.button1.pack()
self.button2 = tk.Button(master, text="车牌检测", command=self.detect_license_plate)
self.button2.pack()
self.button3 = tk.Button(master, text="车牌分割", command=self.segment_license_plate)
self.button3.pack()
self.button4 = tk.Button(master, text="保存结果", command=self.save_image)
self.button4.pack()
self.button5 = tk.Button(master, text="退出", command=master.quit)
self.button5.pack()
# 初始化变量
self.img = None
self.img_gray = None
self.roi = None
self.license_plate = None
def load_image(self):
# 打开文件选择对话框
file_path = filedialog.askopenfilename()
# 读取图片
self.img = cv2.imread(file_path)
# 显示图片
self.show_image(self.img)
def detect_license_plate(self):
# 转化为灰度图像
self.img_gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
# 高斯滤波
self.img_gray = cv2.GaussianBlur(self.img_gray, (3, 3), 0)
# 边缘检测
edges = cv2.Canny(self.img_gray, 100, 200)
# 车牌区域提取
contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
aspect_ratio = float(w) / h
if aspect_ratio > 2 and aspect_ratio < 6 and w > 100 and h > 30:
self.roi = self.img[y:y+h, x:x+w]
break
# 显示结果
self.show_image(self.roi)
def segment_license_plate(self):
# 转化为灰度图像
self.img_gray = cv2.cvtColor(self.roi, cv2.COLOR_BGR2GRAY)
# 二值化
_, self.img_gray = cv2.threshold(self.img_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# 去除噪声
kernel = np.ones((3, 3), np.uint8)
self.img_gray = cv2.morphologyEx(self.img_gray, cv2.MORPH_OPEN, kernel)
# 字符分割
contours, hierarchy = cv2.findContours(self.img_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
x = []
for cnt in contours:
x_, y_, w_, h_ = cv2.boundingRect(cnt)
if w_ > 10 and h_ > 10:
x.append(x_)
x.sort()
for i in range(len(x)):
if i == 0:
self.license_plate = self.roi[:, x[i]:x[i+1]]
elif i == len(x) - 1:
self.license_plate = self.roi[:, x[i]:]
else:
self.license_plate = self.roi[:, x[i]:x[i+1]]
# 保存结果
cv2.imwrite("char_{}.jpg".format(i), self.license_plate)
# 显示结果
self.show_image(self.license_plate)
def save_image(self):
# 打开文件保存对话框
file_path = filedialog.asksaveasfilename(defaultextension=".jpg")
# 保存结果
cv2.imwrite(file_path, self.license_plate)
def show_image(self, img):
# 将OpenCV图像转化为PIL图像
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img)
# 显示图像
img = img.resize((400, 300), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
self.label.configure(image=img)
self.label.image = img
root = tk.Tk()
app = App(root)
root.mainloop()
```
阅读全文