图片分类标注工具
- 运行代码:将代码保存到 Python 文件中并运行。
- 选择文件夹:运行时会弹出对话框,选择要分类的图片文件夹。
- 标注分类:程序会逐张显示图片,你可以在下方输入框中
- 输入类别标签,并点击“Next”按钮记录标签。
- 查看上张:可以使用“Previous”按钮查看上一张图片。
- 保存结果:关闭程序时会自动将所有标签保存到 labels.txt 文件中。
import os
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
class ImageLabeler:
def __init__(self, root, image_folder):
self.root = root
self.root.title("Image Classifier")
self.image_folder = image_folder
self.image_files = [f for f in os.listdir(image_folder) if f.endswith(('.png', '.jpg', '.jpeg'))]
self.current_image_index = 0
self.labels = []
self.photo = None
self.image_label = tk.Label(root)
self.image_label.pack()
self.label_entry = tk.Entry(root)
self.label_entry.pack()
self.next_button = tk.Button(root, text="Next", command=self.next_image)
self.next_button.pack()
self.prev_button = tk.Button(root, text="Previous", command=self.prev_image)
self.prev_button.pack()
self.show_image()
def show_image(self):
if self.current_image_index < len(self.image_files):
image_path = os.path.join(self.image_folder, self.image_files[self.current_image_index])
print(f"Loading image: {image_path}")
try:
image = Image.open(image_path)
image.thumbnail((400, 400))
self.photo = ImageTk.PhotoImage(image)
self.image_label.config(image=self.photo)
self.image_label.image = self.photo
except Exception as e:
print(f"Error loading image {image_path}: {e}")
self.next_image()
else:
self.root.quit()
def next_image(self):
label = self.label_entry.get()
if label:
self.labels.append((self.image_files[self.current_image_index], label))
self.label_entry.delete(0, tk.END)
self.current_image_index += 1
self.show_image()
else:
print("Please enter a label.")
def prev_image(self):
if self.current_image_index > 0:
self.current_image_index -= 1
self.label_entry.delete(0, tk.END)
self.show_image()
def save_labels(self):
with open("labels.txt", "w") as f:
for filename, label in self.labels:
f.write(f"{filename}: {label}\n")
if __name__ == "__main__":
root = tk.Tk()
image_folder = filedialog.askdirectory(title="Select Image Folder")
if image_folder:
app = ImageLabeler(root, image_folder)
root.protocol("WM_DELETE_WINDOW", app.save_labels)
root.mainloop()