python写ui界面,第一步选择文件夹,第二步指定存储路径,第三步,运行按钮,运行后需要检测文件是否是图片格式,第四步生成一个表格,标记识别失败的图片,第五步将识别到的图片文件保存到输出路径,并将生成的表格也保存到输出路径,表格为xlsx格式
时间: 2024-03-02 09:47:50 浏览: 108
好的,这是一个比较复杂的需求,需要使用多个Python库和模块来实现。以下是一个示例代码,可以满足您的要求:
```python
import os
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image
import openpyxl
class ImageRecognitionGUI(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.folder_path = ""
self.output_path = ""
self.images = []
self.failed_images = []
self.create_widgets()
def create_widgets(self):
self.folder_label = tk.Label(self.master, text="请选择文件夹:")
self.folder_label.grid(row=0, column=0, padx=5, pady=5)
self.folder_button = tk.Button(self.master, text="选择文件夹", command=self.select_folder)
self.folder_button.grid(row=0, column=1, padx=5, pady=5)
self.output_label = tk.Label(self.master, text="请选择存储路径:")
self.output_label.grid(row=1, column=0, padx=5, pady=5)
self.output_button = tk.Button(self.master, text="选择路径", command=self.select_output_path)
self.output_button.grid(row=1, column=1, padx=5, pady=5)
self.run_button = tk.Button(self.master, text="运行", command=self.run)
self.run_button.grid(row=2, column=0, columnspan=2, padx=5, pady=5)
def select_folder(self):
self.folder_path = filedialog.askdirectory()
messagebox.showinfo("提示", "已选择文件夹:" + self.folder_path)
def select_output_path(self):
self.output_path = filedialog.askdirectory()
messagebox.showinfo("提示", "已选择输出路径:" + self.output_path)
def run(self):
if not self.folder_path or not self.output_path:
messagebox.showerror("错误", "请选择文件夹和输出路径")
return
self.images = []
self.failed_images = []
for file_name in os.listdir(self.folder_path):
file_path = os.path.join(self.folder_path, file_name)
if os.path.isfile(file_path):
try:
img = Image.open(file_path)
self.images.append(file_path)
except:
self.failed_images.append(file_path)
self.generate_table()
self.save_output()
def generate_table(self):
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "识别结果表格"
row_num = 1
for img in self.images:
ws.cell(row=row_num, column=1, value=img)
row_num += 1
for img in self.failed_images:
ws.cell(row=row_num, column=1, value=img)
ws.cell(row=row_num, column=2, value="识别失败")
row_num += 1
self.table_path = os.path.join(self.output_path, "识别结果表格.xlsx")
wb.save(self.table_path)
def save_output(self):
for img in self.images:
output_path = os.path.join(self.output_path, os.path.basename(img))
os.rename(img, output_path)
messagebox.showinfo("提示", "已完成识别并保存文件和表格")
if __name__ == "__main__":
root = tk.Tk()
root.title("图片识别程序")
root.geometry("300x150")
ImageRecognitionGUI(root).pack()
root.mainloop()
```
这个程序使用了tkinter库来创建一个图形用户界面。首先,用户需要选择文件夹和输出路径,然后点击运行按钮来开始识别图片。程序会检查文件夹中的所有文件,并将其转换成图片格式进行识别,如果识别失败则会标记为失败。最后,程序会生成一个表格来显示识别结果,并将识别成功的图片保存到输出路径中。这个程序可以根据您的需求进行修改和调整。
阅读全文