Update license_recog.py

main
pos97em56 1 year ago
parent 6ed7cee447
commit 5189f8f471

@ -1,144 +1,130 @@
import tkinter as tk import tkinter as tk
from tkinter import ttk, filedialog, messagebox from tkinter import ttk, filedialog, messagebox
from tkinter import Toplevel from tkinter import Toplevel
from PIL import Image, ImageTk from PIL import Image, ImageTk
from ttkbootstrap import Style from ttkbootstrap import Style
import numpy as np import numpy as np
import cv2 import cv2
import os import os
from .image_operations import locate_license_plate, recognize_characters from .image_operations import locate_license_plate, recognize_characters
edge = None edge = None
processed_win = None processed_win = None
def select_image(root, img_container): def select_image(root, img_container):
global edge global edge
img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.jpeg;*.bmp")]) img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.jpeg;*.bmp")])
if img_path: if img_path:
img_path_fixed = os.path.normpath(img_path) img_path_fixed = os.path.normpath(img_path)
img_container['file_path'] = img_path_fixed img_container['file_path'] = img_path_fixed
src_temp = cv2.imdecode(np.fromfile(img_path_fixed, dtype=np.uint8), cv2.IMREAD_UNCHANGED) src_temp = cv2.imdecode(np.fromfile(img_path_fixed, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
if src_temp is None: if src_temp is None:
messagebox.showerror("错误", "无法读取图片,请选择有效的图片路径") messagebox.showerror("错误", "无法读取图片,请选择有效的图片路径")
return return
src = cv2.cvtColor(src_temp, cv2.COLOR_BGR2RGB) src = cv2.cvtColor(src_temp, cv2.COLOR_BGR2RGB)
img_container['image'] = src img_container['image'] = src
if 'img_label' not in img_container or not isinstance(img_container['img_label'], tk.Label): if 'img_label' not in img_container or not isinstance(img_container['img_label'], tk.Label):
img_container['img_label'] = tk.Label(root) img_container['img_label'] = tk.Label(root)
img_container['img_label'].pack(side=tk.TOP, pady=10) img_container['img_label'].pack(side=tk.TOP, pady=10)
img = Image.fromarray(src) img = Image.fromarray(src)
img.thumbnail((200, 200)) img.thumbnail((200, 200))
img_tk = ImageTk.PhotoImage(img) img_tk = ImageTk.PhotoImage(img)
img_container['img_label'].configure(image=img_tk) img_container['img_label'].configure(image=img_tk)
img_container['img_label'].image = img_tk img_container['img_label'].image = img_tk
edge = Image.fromarray(src) edge = Image.fromarray(src)
else: else:
messagebox.showerror("错误", "没有选择图片路径") messagebox.showerror("错误", "没有选择图片路径")
def show_selected_image(root, img_container): def change_size(event, img, label_pic):
if 'file_path' in img_container: img_aspect = img.shape[1] / img.shape[0]
img_path = img_container['file_path'] new_aspect = event.width / event.height
img = Image.open(img_path)
img.thumbnail((800, 800)) if new_aspect > img_aspect:
img_tk = ImageTk.PhotoImage(img) new_width = int(event.height * img_aspect)
if 'img_label' not in img_container: new_height = event.height
img_container['img_label'] = tk.Label(root) else:
img_container['img_label'].pack(side=tk.TOP, pady=10) new_width = event.width
img_container['img_label'].configure(image=img_tk) new_height = int(event.width / img_aspect)
img_container['img_label'].image = img_tk
else: resized_image = cv2.resize(img, (new_width, new_height))
messagebox.showerror("错误", "没有选择图片路径") image_tk = ImageTk.PhotoImage(Image.fromarray(resized_image))
label_pic.image = image_tk
def change_size(event, img, label_pic): label_pic['image'] = image_tk
img_aspect = img.shape[1] / img.shape[0]
new_aspect = event.width / event.height def savefile():
global edge
if new_aspect > img_aspect:
new_width = int(event.height * img_aspect) filename = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG files", "*.jpg"), ("PNG files", "*.png"), ("BMP files", "*.bmp")])
new_height = event.height if not filename:
else: return
new_width = event.width
new_height = int(event.width / img_aspect) if edge is not None:
try:
resized_image = cv2.resize(img, (new_width, new_height)) edge.save(filename)
image_tk = ImageTk.PhotoImage(Image.fromarray(resized_image)) messagebox.showinfo("保存成功", "图片保存成功!")
label_pic.image = image_tk except Exception as e:
label_pic['image'] = image_tk messagebox.showerror("保存失败", f"无法保存图片: {e}")
else:
def savefile(): messagebox.showerror("保存失败", "没有图像可保存")
global edge
def detect_and_show_processed_image(root, img_container):
filename = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG files", "*.jpg"), ("PNG files", "*.png"), ("BMP files", "*.bmp")]) global processed_win, edge
if not filename:
return # 判断是否已经选取图片
if 'file_path' not in img_container or not img_container['file_path']:
if edge is not None: messagebox.showerror("错误", "没有选择图片!")
try: return
edge.save(filename)
messagebox.showinfo("保存成功", "图片保存成功!") file_path = img_container['file_path']
except Exception as e: print(f"File path: {file_path}") # 调试输出文件路径
messagebox.showerror("保存失败", f"无法保存图片: {e}")
else: # 调用图像处理函数
messagebox.showerror("保存失败", "没有图像可保存") processed_img = locate_license_plate(file_path)
def detect_and_show_processed_image(root, img_container): # 识别字符
global processed_win, edge recognized_text = recognize_characters(processed_img)
# 判断是否已经选取图片 # 转换为RGB格式
if 'file_path' not in img_container or not img_container['file_path']: processed_img_rgb = cv2.cvtColor(processed_img, cv2.COLOR_BGR2RGB)
messagebox.showerror("错误", "没有选择图片!")
return # 更新 edge 变量
edge = Image.fromarray(processed_img_rgb)
file_path = img_container['file_path']
print(f"File path: {file_path}") # 调试输出文件路径 # 创建Toplevel窗口
try:
# 调用图像处理函数 processed_win.destroy()
processed_img = locate_license_plate(file_path) except Exception:
print("NVM")
# 识别字符 finally:
recognized_text = recognize_characters(processed_img) processed_win = Toplevel(root)
processed_win.attributes('-topmost', True)
# 转换为RGB格式 processed_win.geometry("360x340")
processed_img_rgb = cv2.cvtColor(processed_img, cv2.COLOR_BGR2RGB) processed_win.resizable(True, True) # 可缩放
processed_win.title("处理后的图像")
# 更新 edge 变量
edge = Image.fromarray(processed_img_rgb) # 显示图像
label_pic = tk.Label(processed_win, text="IMG", width=360, height=240)
# 创建Toplevel窗口 image_tk = ImageTk.PhotoImage(Image.fromarray(processed_img_rgb))
try: label_pic.image = image_tk
processed_win.destroy() label_pic['image'] = image_tk
except Exception:
print("NVM") label_pic.bind('<Configure>', lambda event: change_size(event, processed_img_rgb, label_pic))
finally: label_pic.pack(fill=tk.BOTH, expand=tk.YES)
processed_win = Toplevel(root)
processed_win.attributes('-topmost', True) # 显示识别结果
processed_win.geometry("360x340") result_label = tk.Label(processed_win, text=f"识别结果: {recognized_text}")
processed_win.resizable(True, True) # 可缩放 result_label.pack(side=tk.TOP, pady=10)
processed_win.title("处理后的图像")
# 添加保存按钮
# 显示图像 btn_save = tk.Button(processed_win, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20,
label_pic = tk.Label(processed_win, text="IMG", width=360, height=240) command=savefile)
image_tk = ImageTk.PhotoImage(Image.fromarray(processed_img_rgb)) btn_save.pack(pady=10)
label_pic.image = image_tk
label_pic['image'] = image_tk
label_pic.bind('<Configure>', lambda event: change_size(event, processed_img_rgb, label_pic))
label_pic.pack(fill=tk.BOTH, expand=tk.YES)
# 显示识别结果
result_label = tk.Label(processed_win, text=f"识别结果: {recognized_text}")
result_label.pack(side=tk.TOP, pady=10)
# 添加保存按钮
btn_save = tk.Button(processed_win, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20,
command=savefile)
btn_save.pack(pady=10)
return return
Loading…
Cancel
Save