- Implemented parallel execution for OCR tasks, significantly improving recognition speed for content, countdown, and value detection. - Updated configuration settings to support automatic cleanup of debug captures, including retention days and maximum file limits. - Enhanced GUI to include new options for debugging parameters, allowing users to configure debug capture settings directly. - Improved documentation to reflect changes in OCR functionality and debugging features, ensuring clarity for users. - Refined error handling and logging across various modules to facilitate better monitoring and troubleshooting.
207 lines
7.3 KiB
Python
207 lines
7.3 KiB
Python
import sys
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
from PIL import Image, ImageTk
|
|
|
|
try:
|
|
import tkinter as tk
|
|
from tkinter import filedialog
|
|
except Exception as e:
|
|
raise SystemExit(f"tkinter 不可用:{e}\n请安装带 tkinter 的 Python,或改用画图/PS/GIMP 取坐标。")
|
|
|
|
|
|
def clamp(v: float, lo: float, hi: float) -> float:
|
|
return lo if v < lo else hi if v > hi else v
|
|
|
|
|
|
class CoordPicker:
|
|
def __init__(self, image_path: Optional[Path]):
|
|
self.image_path: Optional[Path] = None
|
|
self.img: Optional[Image.Image] = None
|
|
self.w = 0
|
|
self.h = 0
|
|
self.scale = 1.0
|
|
self.disp_w = 0
|
|
self.disp_h = 0
|
|
self.tk_img = None
|
|
self.file_list: list[Path] = []
|
|
self.file_idx: int = -1
|
|
|
|
self.root = tk.Tk()
|
|
|
|
# 菜单 + 快捷键
|
|
menubar = tk.Menu(self.root)
|
|
file_menu = tk.Menu(menubar, tearoff=0)
|
|
file_menu.add_command(label="打开...", command=self.open_dialog, accelerator="Ctrl+O")
|
|
file_menu.add_command(label="上一张", command=self.prev_image, accelerator="← / PageUp")
|
|
file_menu.add_command(label="下一张", command=self.next_image, accelerator="→ / PageDown")
|
|
file_menu.add_separator()
|
|
file_menu.add_command(label="退出", command=self.root.destroy)
|
|
menubar.add_cascade(label="文件", menu=file_menu)
|
|
self.root.config(menu=menubar)
|
|
self.root.bind_all("<Control-o>", lambda e: self.open_dialog())
|
|
self.root.bind("<Left>", lambda e: self.prev_image())
|
|
self.root.bind("<Right>", lambda e: self.next_image())
|
|
self.root.bind("<Prior>", lambda e: self.prev_image()) # PageUp
|
|
self.root.bind("<Next>", lambda e: self.next_image()) # PageDown
|
|
|
|
self.canvas = tk.Canvas(self.root, width=800, height=600)
|
|
self.canvas.pack(fill=tk.BOTH, expand=False)
|
|
self._canvas_image_id = self.canvas.create_image(0, 0, anchor=tk.NW)
|
|
|
|
self.status = tk.StringVar()
|
|
self.status.set("移动鼠标查看坐标;单击复制坐标;Ctrl+O 打开图片")
|
|
self.label = tk.Label(self.root, textvariable=self.status, anchor="w")
|
|
self.label.pack(fill=tk.X)
|
|
|
|
self.canvas.bind("<Motion>", self.on_move)
|
|
self.canvas.bind("<Button-1>", self.on_click)
|
|
|
|
if image_path is None:
|
|
if not self.open_dialog():
|
|
raise SystemExit(2)
|
|
else:
|
|
self.set_image(image_path, update_list=True)
|
|
|
|
def _refresh_file_list(self, current: Path) -> None:
|
|
"""刷新当前目录下的图片列表,并定位当前索引。"""
|
|
exts = {".png", ".jpg", ".jpeg", ".bmp", ".webp"}
|
|
try:
|
|
files = [p for p in current.parent.iterdir() if p.suffix.lower() in exts and p.is_file()]
|
|
files.sort()
|
|
self.file_list = files
|
|
try:
|
|
self.file_idx = self.file_list.index(current)
|
|
except ValueError:
|
|
self.file_idx = -1
|
|
except Exception:
|
|
self.file_list = []
|
|
self.file_idx = -1
|
|
|
|
def set_image(self, image_path: Path, update_list: bool = False) -> None:
|
|
image_path = Path(image_path)
|
|
self.image_path = image_path
|
|
self.img = Image.open(image_path).convert("RGB")
|
|
self.w, self.h = self.img.size
|
|
|
|
if update_list:
|
|
self._refresh_file_list(image_path)
|
|
|
|
# 显示用缩放(不改变输出坐标)
|
|
screen_w = self.root.winfo_screenwidth()
|
|
screen_h = self.root.winfo_screenheight()
|
|
max_w = int(screen_w * 0.9)
|
|
max_h = int(screen_h * 0.85)
|
|
scale_w = max_w / max(1, self.w)
|
|
scale_h = max_h / max(1, self.h)
|
|
self.scale = min(1.0, scale_w, scale_h)
|
|
self.disp_w = int(self.w * self.scale)
|
|
self.disp_h = int(self.h * self.scale)
|
|
|
|
disp_img = self.img
|
|
if self.scale < 1.0:
|
|
try:
|
|
resample = Image.Resampling.BICUBIC # Pillow>=9
|
|
except Exception:
|
|
resample = Image.BICUBIC # older Pillow
|
|
disp_img = self.img.resize((self.disp_w, self.disp_h), resample)
|
|
|
|
self.tk_img = ImageTk.PhotoImage(disp_img)
|
|
self.canvas.config(width=self.disp_w, height=self.disp_h)
|
|
self.canvas.itemconfig(self._canvas_image_id, image=self.tk_img)
|
|
self.root.title(f"取坐标: {image_path} ({self.w}x{self.h})")
|
|
|
|
def open_dialog(self) -> bool:
|
|
initial_dir = None
|
|
try:
|
|
if self.image_path and self.image_path.parent.exists():
|
|
initial_dir = str(self.image_path.parent)
|
|
except Exception:
|
|
initial_dir = None
|
|
|
|
filename = filedialog.askopenfilename(
|
|
title="选择图片",
|
|
initialdir=initial_dir,
|
|
filetypes=[
|
|
("Images", "*.png;*.jpg;*.jpeg;*.bmp;*.webp"),
|
|
("All files", "*.*"),
|
|
],
|
|
)
|
|
if not filename:
|
|
return False
|
|
try:
|
|
self.set_image(Path(filename), update_list=True)
|
|
return True
|
|
except Exception as e:
|
|
self.status.set(f"打开失败: {e}")
|
|
return False
|
|
|
|
def _to_image_xy(self, event) -> tuple[int, int]:
|
|
if not self.img or self.w <= 0 or self.h <= 0:
|
|
return 0, 0
|
|
x = int(clamp(event.x / self.scale, 0, self.w - 1))
|
|
y = int(clamp(event.y / self.scale, 0, self.h - 1))
|
|
return x, y
|
|
|
|
def on_move(self, event):
|
|
x, y = self._to_image_xy(event)
|
|
self.status.set(f"x={x}, y={y}")
|
|
|
|
def on_click(self, event):
|
|
x, y = self._to_image_xy(event)
|
|
text = f"{x},{y}"
|
|
print(text)
|
|
try:
|
|
self.root.clipboard_clear()
|
|
self.root.clipboard_append(text)
|
|
self.status.set(f"已复制: {text}")
|
|
except Exception:
|
|
self.status.set(f"坐标: {text} (复制失败)")
|
|
|
|
def _load_by_index(self, idx: int) -> bool:
|
|
if not self.file_list:
|
|
return False
|
|
idx = idx % len(self.file_list)
|
|
try:
|
|
self.set_image(self.file_list[idx], update_list=False)
|
|
self.file_idx = idx
|
|
return True
|
|
except Exception as e:
|
|
self.status.set(f"切换失败: {e}")
|
|
return False
|
|
|
|
def next_image(self) -> None:
|
|
if self.file_list:
|
|
if self._load_by_index(self.file_idx + 1):
|
|
self.status.set(f"下一张: {self.image_path.name if self.image_path else ''}")
|
|
|
|
def prev_image(self) -> None:
|
|
if self.file_list:
|
|
if self._load_by_index(self.file_idx - 1):
|
|
self.status.set(f"上一张: {self.image_path.name if self.image_path else ''}")
|
|
|
|
def run(self):
|
|
self.root.mainloop()
|
|
|
|
|
|
def main(argv: list[str]) -> int:
|
|
p: Optional[Path] = None
|
|
if len(argv) >= 2:
|
|
p = Path(argv[1]).expanduser()
|
|
if p and not p.is_absolute():
|
|
p = (Path(__file__).resolve().parent.parent / p).resolve()
|
|
if p and not p.exists():
|
|
print(f"找不到图片: {p}")
|
|
print("将弹出文件选择框,请手动选择图片。")
|
|
p = None
|
|
else:
|
|
print("未传入图片路径,将弹出文件选择框。")
|
|
|
|
CoordPicker(p).run()
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main(sys.argv))
|