- Removed obsolete command-line test parameters from `run_cli.py` to streamline functionality. - Introduced a new `ocr_preprocess.py` module for unified OCR image preprocessing, enhancing recognition stability. - Updated various components to utilize the new preprocessing function, improving code organization and readability. - Adjusted configuration values in `config.json` for better performance and consistency. - Added comprehensive technical documentation for the Douyin project, detailing code modification standards and operational guidelines. - Cleaned up excessive blank lines across multiple files to enhance overall readability.
533 lines
20 KiB
Python
533 lines
20 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 取坐标。")
|
||
|
||
# 尝试导入拖放支持库
|
||
try:
|
||
from tkinterdnd2 import DND_FILES, TkinterDnD
|
||
HAS_DND = True
|
||
except ImportError:
|
||
HAS_DND = False
|
||
TkinterDnD = None
|
||
|
||
|
||
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.min_scale = 0.1 # 最小缩放比例
|
||
self.max_scale = 10.0 # 最大缩放比例
|
||
self.disp_w = 0
|
||
self.disp_h = 0
|
||
self.tk_img = None
|
||
self.file_list: list[Path] = []
|
||
self.file_idx: int = -1
|
||
self.zoom_center_x = 0 # 缩放中心点
|
||
self.zoom_center_y = 0
|
||
self.scroll_offset_x = 0 # 滚动偏移
|
||
self.scroll_offset_y = 0
|
||
self.magnifier_window = None # 放大镜窗口
|
||
self.magnifier_size = 200 # 放大镜窗口大小
|
||
self.magnifier_zoom = 8 # 放大倍数
|
||
|
||
# 使用 TkinterDnD 支持拖放(如果可用)
|
||
if HAS_DND and TkinterDnD is not None:
|
||
self.root = TkinterDnD.Tk()
|
||
else:
|
||
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)
|
||
|
||
view_menu = tk.Menu(menubar, tearoff=0)
|
||
view_menu.add_command(label="放大 (+)", command=self.zoom_in, accelerator="+ / Ctrl+滚轮上")
|
||
view_menu.add_command(label="缩小 (-)", command=self.zoom_out, accelerator="- / Ctrl+滚轮下")
|
||
view_menu.add_command(label="重置缩放 (1:1)", command=self.reset_zoom, accelerator="Ctrl+0")
|
||
view_menu.add_separator()
|
||
view_menu.add_command(label="显示/隐藏放大镜", command=self.toggle_magnifier, accelerator="M")
|
||
menubar.add_cascade(label="视图", menu=view_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.root.bind("<plus>", lambda e: self.zoom_in())
|
||
self.root.bind("<equal>", lambda e: self.zoom_in()) # 无Shift的+键
|
||
self.root.bind("<minus>", lambda e: self.zoom_out())
|
||
self.root.bind("<Control-0>", lambda e: self.reset_zoom())
|
||
self.root.bind("<Key-m>", lambda e: self.toggle_magnifier())
|
||
self.root.bind("<Key-M>", lambda e: self.toggle_magnifier())
|
||
|
||
self.canvas = tk.Canvas(self.root, width=800, height=600)
|
||
self.canvas.pack(fill=tk.BOTH, expand=True)
|
||
self._canvas_image_id = self.canvas.create_image(0, 0, anchor=tk.NW)
|
||
|
||
self.status = tk.StringVar()
|
||
if HAS_DND:
|
||
self.status.set("移动鼠标查看坐标;单击复制坐标;滚轮缩放;右键显示放大镜;Ctrl+O 打开图片;或直接拖放图片到窗口")
|
||
else:
|
||
self.status.set("移动鼠标查看坐标;单击复制坐标;滚轮缩放;右键显示放大镜;Ctrl+O 打开图片(提示:安装 tkinterdnd2 可支持拖放)")
|
||
self.label = tk.Label(self.root, textvariable=self.status, anchor="w")
|
||
self.label.pack(fill=tk.X)
|
||
|
||
# 像素信息显示
|
||
self.pixel_info = tk.StringVar()
|
||
self.pixel_info.set("")
|
||
self.pixel_label = tk.Label(self.root, textvariable=self.pixel_info, anchor="w", font=("Courier", 10))
|
||
self.pixel_label.pack(fill=tk.X)
|
||
|
||
self.canvas.bind("<Motion>", self.on_move)
|
||
self.canvas.bind("<Button-1>", self.on_click)
|
||
self.canvas.bind("<Button-3>", self.on_right_click) # 右键显示放大镜
|
||
self.canvas.bind("<MouseWheel>", self.on_mousewheel) # Windows/Linux
|
||
self.canvas.bind("<Button-4>", self.on_mousewheel) # Linux
|
||
self.canvas.bind("<Button-5>", self.on_mousewheel) # Linux
|
||
self.canvas.bind("<Control-MouseWheel>", self.on_mousewheel_ctrl) # Ctrl+滚轮
|
||
self.canvas.bind("<B1-Motion>", self.on_drag) # 拖拽平移
|
||
self.canvas.bind("<ButtonPress-1>", self.on_drag_start)
|
||
self.canvas.bind("<ButtonRelease-1>", self.on_drag_end)
|
||
self.drag_start_x = 0
|
||
self.drag_start_y = 0
|
||
self.is_dragging = False
|
||
|
||
# 添加拖放支持
|
||
if HAS_DND:
|
||
self.root.drop_target_register(DND_FILES)
|
||
self.root.dnd_bind('<<Drop>>', self.on_drop)
|
||
self.canvas.drop_target_register(DND_FILES)
|
||
self.canvas.dnd_bind('<<Drop>>', self.on_drop)
|
||
self.label.drop_target_register(DND_FILES)
|
||
self.label.dnd_bind('<<Drop>>', self.on_drop)
|
||
|
||
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)
|
||
|
||
# 显示用缩放(不改变输出坐标)
|
||
self._update_display()
|
||
self.root.title(f"取坐标: {image_path} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x")
|
||
|
||
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
|
||
# 把canvas坐标转换为图像坐标(考虑缩放和滚动偏移)
|
||
canvas_x = event.x + self.scroll_offset_x
|
||
canvas_y = event.y + self.scroll_offset_y
|
||
x = int(clamp(canvas_x / self.scale, 0, self.w - 1))
|
||
y = int(clamp(canvas_y / self.scale, 0, self.h - 1))
|
||
return x, y
|
||
|
||
def _update_display(self):
|
||
"""更新显示"""
|
||
if not self.img:
|
||
return
|
||
|
||
# 获取canvas实际大小
|
||
self.root.update_idletasks()
|
||
canvas_w = max(1, self.canvas.winfo_width())
|
||
canvas_h = max(1, self.canvas.winfo_height())
|
||
|
||
# 计算显示尺寸
|
||
self.disp_w = int(self.w * self.scale)
|
||
self.disp_h = int(self.h * self.scale)
|
||
|
||
# 限制滚动偏移
|
||
max_offset_x = max(0, self.disp_w - canvas_w)
|
||
max_offset_y = max(0, self.disp_h - canvas_h)
|
||
self.scroll_offset_x = max(0, min(self.scroll_offset_x, max_offset_x))
|
||
self.scroll_offset_y = max(0, min(self.scroll_offset_y, max_offset_y))
|
||
|
||
# 生成显示图像
|
||
try:
|
||
resample = Image.Resampling.BICUBIC if hasattr(Image, 'Resampling') else Image.BICUBIC
|
||
except Exception:
|
||
resample = Image.BICUBIC
|
||
|
||
if self.scale != 1.0:
|
||
# 如果放大,只显示可见区域以提高性能
|
||
if self.scale > 1.0 and canvas_w < self.disp_w and canvas_h < self.disp_h:
|
||
# 计算原图中要显示的区域
|
||
src_x1 = max(0, int(self.scroll_offset_x / self.scale))
|
||
src_y1 = max(0, int(self.scroll_offset_y / self.scale))
|
||
src_x2 = min(self.w, src_x1 + int(canvas_w / self.scale) + 2)
|
||
src_y2 = min(self.h, src_y1 + int(canvas_h / self.scale) + 2)
|
||
|
||
# 裁剪并放大
|
||
crop_img = self.img.crop((src_x1, src_y1, src_x2, src_y2))
|
||
crop_w, crop_h = crop_img.size
|
||
disp_img = crop_img.resize((int(crop_w * self.scale), int(crop_h * self.scale)), resample)
|
||
else:
|
||
# 缩小或完全显示
|
||
disp_img = self.img.resize((self.disp_w, self.disp_h), resample)
|
||
else:
|
||
disp_img = self.img
|
||
|
||
self.tk_img = ImageTk.PhotoImage(disp_img)
|
||
|
||
# 更新canvas滚动区域
|
||
self.canvas.config(scrollregion=(0, 0, self.disp_w, self.disp_h))
|
||
|
||
# 更新图像位置
|
||
self.canvas.coords(self._canvas_image_id, -self.scroll_offset_x, -self.scroll_offset_y)
|
||
self.canvas.itemconfig(self._canvas_image_id, image=self.tk_img)
|
||
|
||
# 更新标题
|
||
if self.image_path:
|
||
self.root.title(f"取坐标: {self.image_path.name} ({self.w}x{self.h}) | 缩放: {self.scale:.2f}x")
|
||
|
||
def on_move(self, event):
|
||
"""移动鼠标:显示坐标和像素信息(保留你原来的坐标逻辑)"""
|
||
x, y = self._to_image_xy(event)
|
||
rgb_info = ""
|
||
if self.img and 0 <= x < self.w and 0 <= y < self.h:
|
||
try:
|
||
pixel = self.img.getpixel((x, y))
|
||
if isinstance(pixel, tuple) and len(pixel) >= 3:
|
||
rgb_info = f" | RGB({pixel[0]}, {pixel[1]}, {pixel[2]})"
|
||
elif isinstance(pixel, int):
|
||
rgb_info = f" | Gray({pixel})"
|
||
except Exception:
|
||
pass
|
||
|
||
self.status.set(f"x={x}, y={y}{rgb_info}")
|
||
self.pixel_info.set(f"像素位置: ({x}, {y}){rgb_info}")
|
||
|
||
# 更新放大镜
|
||
if self.magnifier_window and self.magnifier_window.winfo_exists():
|
||
self._update_magnifier(x, 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.root.update_idletasks()
|
||
self.status.set(f"已复制: {text}")
|
||
except Exception:
|
||
self.status.set(f"坐标: {text} (复制失败)")
|
||
|
||
def on_right_click(self, event):
|
||
"""右键显示/隐藏放大镜"""
|
||
self.toggle_magnifier()
|
||
|
||
def on_drag_start(self, event):
|
||
"""开始拖拽"""
|
||
self.drag_start_x = event.x
|
||
self.drag_start_y = event.y
|
||
self.is_dragging = False
|
||
|
||
def on_drag(self, event):
|
||
"""拖拽平移"""
|
||
if not self.img:
|
||
return
|
||
dx = event.x - self.drag_start_x
|
||
dy = event.y - self.drag_start_y
|
||
if abs(dx) > 5 or abs(dy) > 5: # 避免误触
|
||
self.is_dragging = True
|
||
self.scroll_offset_x -= dx
|
||
self.scroll_offset_y -= dy
|
||
self.drag_start_x = event.x
|
||
self.drag_start_y = event.y
|
||
self._update_display()
|
||
|
||
def on_drag_end(self, event):
|
||
"""结束拖拽"""
|
||
self.is_dragging = False
|
||
|
||
def on_mousewheel(self, event):
|
||
"""鼠标滚轮缩放(无Ctrl)"""
|
||
if event.state & 0x4: # Ctrl键按下
|
||
return # 交给on_mousewheel_ctrl处理
|
||
|
||
delta = 0
|
||
if event.num == 4 or event.delta > 0: # 向上滚动
|
||
delta = 1
|
||
elif event.num == 5 or event.delta < 0: # 向下滚动
|
||
delta = -1
|
||
|
||
if delta != 0:
|
||
x, y = self._to_image_xy(event)
|
||
self._zoom_at_point(x, y, delta * 0.1)
|
||
|
||
def on_mousewheel_ctrl(self, event):
|
||
"""Ctrl+滚轮缩放"""
|
||
delta = 0
|
||
if event.num == 4 or event.delta > 0: # 向上滚动
|
||
delta = 1
|
||
elif event.num == 5 or event.delta < 0: # 向下滚动
|
||
delta = -1
|
||
|
||
if delta != 0:
|
||
x, y = self._to_image_xy(event)
|
||
self._zoom_at_point(x, y, delta * 0.1)
|
||
|
||
def _zoom_at_point(self, img_x: int, img_y: int, delta: float):
|
||
"""在指定点缩放"""
|
||
if not self.img:
|
||
return
|
||
|
||
old_scale = self.scale
|
||
new_scale = clamp(old_scale + delta, self.min_scale, self.max_scale)
|
||
|
||
if abs(new_scale - old_scale) < 0.01:
|
||
return
|
||
|
||
# 计算缩放中心点在图像中的位置
|
||
# 调整滚动偏移,使缩放点保持在屏幕上的同一位置
|
||
scale_ratio = new_scale / old_scale
|
||
self.scroll_offset_x = img_x * new_scale - (img_x * old_scale - self.scroll_offset_x) * scale_ratio
|
||
self.scroll_offset_y = img_y * new_scale - (img_y * old_scale - self.scroll_offset_y) * scale_ratio
|
||
|
||
self.scale = new_scale
|
||
self._update_display()
|
||
|
||
def zoom_in(self):
|
||
"""放大"""
|
||
if not self.img:
|
||
return
|
||
center_x = self.w // 2
|
||
center_y = self.h // 2
|
||
self._zoom_at_point(center_x, center_y, 0.2)
|
||
|
||
def zoom_out(self):
|
||
"""缩小"""
|
||
if not self.img:
|
||
return
|
||
center_x = self.w // 2
|
||
center_y = self.h // 2
|
||
self._zoom_at_point(center_x, center_y, -0.2)
|
||
|
||
def reset_zoom(self):
|
||
"""重置缩放"""
|
||
if not self.img:
|
||
return
|
||
self.scale = 1.0
|
||
self.scroll_offset_x = 0
|
||
self.scroll_offset_y = 0
|
||
self._update_display()
|
||
|
||
def toggle_magnifier(self):
|
||
"""切换放大镜显示"""
|
||
if self.magnifier_window and self.magnifier_window.winfo_exists():
|
||
self.magnifier_window.destroy()
|
||
self.magnifier_window = None
|
||
else:
|
||
self._create_magnifier()
|
||
|
||
def _create_magnifier(self):
|
||
"""创建放大镜窗口"""
|
||
if not self.img:
|
||
return
|
||
|
||
self.magnifier_window = tk.Toplevel(self.root)
|
||
self.magnifier_window.title("放大镜")
|
||
self.magnifier_window.geometry(f"{self.magnifier_size}x{self.magnifier_size}")
|
||
self.magnifier_window.resizable(False, False)
|
||
|
||
self.magnifier_canvas = tk.Canvas(
|
||
self.magnifier_window,
|
||
width=self.magnifier_size,
|
||
height=self.magnifier_size,
|
||
highlightthickness=1,
|
||
highlightbackground="black"
|
||
)
|
||
self.magnifier_canvas.pack()
|
||
|
||
# 绑定鼠标移动
|
||
self.root.bind("<Motion>", self._on_magnifier_move)
|
||
|
||
def _on_magnifier_move(self, event):
|
||
"""鼠标移动时更新放大镜"""
|
||
if not self.magnifier_window or not self.magnifier_window.winfo_exists():
|
||
return
|
||
|
||
x, y = self._to_image_xy(event)
|
||
self._update_magnifier(x, y)
|
||
|
||
def _update_magnifier(self, img_x: int, img_y: int):
|
||
"""更新放大镜显示"""
|
||
if not self.magnifier_window or not self.magnifier_window.winfo_exists() or not self.img:
|
||
return
|
||
|
||
# 计算放大区域
|
||
half_size = self.magnifier_size // (2 * self.magnifier_zoom)
|
||
x1 = max(0, img_x - half_size)
|
||
y1 = max(0, img_y - half_size)
|
||
x2 = min(self.w, img_x + half_size)
|
||
y2 = min(self.h, img_y + half_size)
|
||
|
||
# 裁剪并放大
|
||
crop_img = self.img.crop((x1, y1, x2, y2))
|
||
try:
|
||
resample = Image.Resampling.NEAREST if hasattr(Image, 'Resampling') else Image.NEAREST
|
||
except Exception:
|
||
resample = Image.NEAREST
|
||
magnified = crop_img.resize((self.magnifier_size, self.magnifier_size), resample)
|
||
|
||
# 显示
|
||
tk_mag_img = ImageTk.PhotoImage(magnified)
|
||
self.magnifier_canvas.delete("all")
|
||
self.magnifier_canvas.create_image(self.magnifier_size // 2, self.magnifier_size // 2, image=tk_mag_img)
|
||
self.magnifier_canvas.image = tk_mag_img # 保持引用
|
||
|
||
# 绘制十字线
|
||
center = self.magnifier_size // 2
|
||
self.magnifier_canvas.create_line(center, 0, center, self.magnifier_size, fill="red", width=1)
|
||
self.magnifier_canvas.create_line(0, center, self.magnifier_size, center, fill="red", width=1)
|
||
|
||
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 on_drop(self, event) -> None:
|
||
"""处理拖放事件"""
|
||
if not HAS_DND:
|
||
return
|
||
|
||
try:
|
||
# 获取拖放的文件路径
|
||
files = self.root.tk.splitlist(event.data)
|
||
if not files:
|
||
return
|
||
|
||
# 取第一个文件
|
||
file_path = files[0]
|
||
# 移除可能的花括号(Windows 拖放可能包含)
|
||
file_path = file_path.strip('{}')
|
||
|
||
path = Path(file_path)
|
||
if not path.exists():
|
||
self.status.set(f"文件不存在: {path}")
|
||
return
|
||
|
||
# 检查是否为图片文件
|
||
exts = {".png", ".jpg", ".jpeg", ".bmp", ".webp"}
|
||
if path.suffix.lower() not in exts:
|
||
self.status.set(f"不是支持的图片格式: {path.suffix}")
|
||
return
|
||
|
||
# 加载图片
|
||
self.set_image(path, update_list=True)
|
||
self.status.set(f"已加载: {path.name}")
|
||
except Exception as e:
|
||
self.status.set(f"拖放失败: {e}")
|
||
|
||
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)) |