diff --git a/assets/coupon.png b/assets/coupon.png new file mode 100644 index 0000000..2f1a443 Binary files /dev/null and b/assets/coupon.png differ diff --git a/assets/fudai1.png b/assets/fudai1.png deleted file mode 100644 index 7b7f832..0000000 Binary files a/assets/fudai1.png and /dev/null differ diff --git a/assets/xiangqing.png b/assets/xiangqing.png new file mode 100644 index 0000000..c4c5856 Binary files /dev/null and b/assets/xiangqing.png differ diff --git a/config.json b/config.json index 07dec22..325ddd8 100644 --- a/config.json +++ b/config.json @@ -41,7 +41,7 @@ ], "fudai_quiet_hours_enabled": true, "fudai_quiet_start_hour": 2, - "fudai_quiet_end_hour": 6, + "fudai_quiet_end_hour": 9, "yanghao_enabled": false, "yanghao_enable_actions": false, "yanghao_like_icon_x": 0, @@ -67,5 +67,6 @@ "stage_diag_max_step_time": 4.0, "live_room_match_threshold": 0.7, "enable_ocr_mode1": false, - "fudai_template_match_threshold": 0.2 + "fudai_template_match_threshold": 0.5, + "lucky_draw_red_ratio_threshold": 0.9 } diff --git a/douyin_detection.py b/douyin_detection.py index 2d14331..d7ffa9f 100644 --- a/douyin_detection.py +++ b/douyin_detection.py @@ -132,17 +132,114 @@ def check_detail_height(analyser: Any) -> int: def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool = False): - """Check whether the live-room screen currently has a fudai icon. - - 使用模板匹配进行检测(暂时关闭像素检测): - - 使用 assets/fudai.png 作为模板进行匹配 - - 在指定区域内搜索福袋图标 - """ + """判定直播页面福袋的小图标是否存在(像素检测版)。""" func_start = time.time() path = os.path.join(os.path.dirname(__file__), "pic") pic1_path = os.path.join(path, "screenshot.png") attempt_count = 0 # 仅用于日志记录,不影响循环控制 + # ===== 像素检测版(优先使用),不依赖 OpenCV ===== + try: + retry_delay_s = float(getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6) + except Exception: + retry_delay_s = 0.6 + try: + max_wait_s = float(getattr(analyser, "fudai_icon_max_wait_seconds", 4.0) or 4.0) + except Exception: + max_wait_s = 4.0 + if retry_delay_s < 0.2: + retry_delay_s = 0.2 + if max_wait_s < 0: + max_wait_s = 0.0 + + max_loops = int(max(2, min(12, (max_wait_s / retry_delay_s) + 1))) + try: + user_max = int(getattr(analyser, "fudai_find_max_attempts", 5) or 5) + except Exception: + user_max = 5 + max_loops = int(min(max_loops, max(1, user_max))) + + loop = 0 + while loop < max_loops: + if not (screenshot_ready and loop == 0): + try: + analyser._shot_and_diagnose("找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False) + except Exception: + pass + + try: + pic = Image.open(pic1_path) + pic.load() + except Exception: + try: + analyser.operation.get_screenshot(analyser.device_id) + except Exception: + pass + loop += 1 + if loop < max_loops: + try: + analyser.operation.delay(retry_delay_s) + except Exception: + time.sleep(retry_delay_s) + continue + + img = pic.convert("RGBA") + width, height = img.size + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + except Exception: + rx = 1080 + try: + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + ry = 2400 + try: + y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) + except Exception: + y_pianyi_val = 0 + + # 扫描 y=403 一带的水平带(与原始脚本一致),按分辨率和 y_pianyi 缩放 + scan_y = 403 * ry // 2400 + y_pianyi_val + scan_x_start = 41 * rx // 1080 + scan_x_end = min(410 * rx // 1080, width) + + if 0 <= scan_y < height and scan_x_start < scan_x_end: + pix = img.load() + detected_x = None + for offset_y in [0, -1, 1, -2, 2]: + check_y = scan_y + offset_y + if not (0 <= check_y < height): + continue + for x_scaled in range(scan_x_start, scan_x_end): + try: + px = pix[x_scaled, check_y] + if ( + isinstance(px, tuple) + and len(px) >= 3 + and 190 <= int(px[0]) <= 206 + and 173 <= int(px[1]) <= 196 + and 234 <= int(px[2]) <= 250 + ): + detected_x = int(x_scaled * 1080.0 / max(1, rx)) + break + except Exception: + continue + if detected_x is not None: + break + + if detected_x is not None: + return detected_x + + loop += 1 + if loop < max_loops: + try: + analyser.operation.delay(retry_delay_s) + except Exception: + time.sleep(retry_delay_s) + + # 像素检测未找到时,返回 False + return False + try: retry_delay_s = float(getattr(analyser, "fudai_icon_retry_delay_seconds", 0.3) or 0.3) except Exception: @@ -247,12 +344,12 @@ def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool except Exception: y_pianyi_val = 0 - # 定义搜索区域 - # X范围:34-382(1080基准) - # Y范围:357-451(2400基准),福袋图标所在高度 - search_x1 = max(0, 34 * rx // 1080) - search_x2 = min(screenshot_img.shape[1], 382 * rx // 1080) - search_y1_base = 357 * ry // 2400 + y_pianyi_val + # 定义搜索区域(仅在更小的范围内寻找福袋图标) + # X范围:160-269(1080基准) + # Y范围:348-451(2400基准) + search_x1 = max(0, 160 * rx // 1080) + search_x2 = min(screenshot_img.shape[1], 269 * rx // 1080) + search_y1_base = 348 * ry // 2400 + y_pianyi_val search_y2_base = 451 * ry // 2400 + y_pianyi_val search_y1 = max(0, search_y1_base) search_y2 = min(screenshot_img.shape[0], search_y2_base) diff --git a/douyin_flow_control.py b/douyin_flow_control.py index 455563c..6e38d2e 100644 --- a/douyin_flow_control.py +++ b/douyin_flow_control.py @@ -149,12 +149,7 @@ def filter_fudai_detail( swipe_up_switch_callback, add_reservation_callback, ) -> bool: - """福袋详情过滤逻辑:根据 config.json 中的配置决定是否丢弃该福袋。 - - 返回: - True 表示"已丢弃/已处理",上层不再参与; - False 表示"不过滤",可继续参与抽奖。 - """ + """福袋详情过滤逻辑:根据 config.json 对福袋进行基础筛选。""" skip, reason = should_skip_fudai_by_config(analyser, detail) try: content = str(detail[0] or "") if isinstance(detail, tuple) and len(detail) >= 1 else "" @@ -171,10 +166,8 @@ def filter_fudai_detail( pass if not skip: - # 返回 False 表示"不丢弃",保留该福袋 return False - - # 需要丢弃:先关闭详情 + try: close_detail_callback(analyser) except Exception: @@ -182,8 +175,7 @@ def filter_fudai_detail( analyser.operation.click_back(analyser.device_id) except Exception: pass - - # 如允许切换,则顺便切到下一个直播间 + if needswitch and swipe_up_switch_callback: try: swipe_up_switch_callback() @@ -196,3 +188,4 @@ def filter_fudai_detail( return True return False + diff --git a/douyin_fudai.py b/douyin_fudai.py index 4179c02..6749e31 100644 --- a/douyin_fudai.py +++ b/douyin_fudai.py @@ -75,6 +75,8 @@ class fudai_analyse: # fudai_find_max_attempts 已废弃,保留仅为兼容性,实际不再使用 self.fudai_find_max_attempts: int = 10 self.screenshot_diagnose_min_interval_seconds: float = 8.0 + # 开奖页面检测红色占比阈值(0.0~1.0) + self.lucky_draw_red_ratio_threshold: float = 0.9 # 直播间检测阈值(模板匹配阈值,0.0~1.0,默认0.8) self.live_room_match_threshold: float = 0.8 @@ -84,6 +86,14 @@ class fudai_analyse: # 初次加载配置 self.load_config() + # ===== 兼容原始脚本的一些简单封装方法 ===== + def click(self, x: int, y: int) -> None: + """兼容原版 fudai_analyse.click:转发到底层 operation.click。""" + try: + self.operation.click(self.device_id, int(x), int(y)) + except Exception: + pass + def load_config(self) -> None: """从 config.json 加载与福袋筛选/节流相关的关键参数(精简版)。""" import json @@ -145,6 +155,14 @@ class fudai_analyse: "screenshot_diagnose_min_interval_seconds", self.screenshot_diagnose_min_interval_seconds, ) + self.lucky_draw_red_ratio_threshold = _float( + "lucky_draw_red_ratio_threshold", + self.lucky_draw_red_ratio_threshold, + ) + if self.lucky_draw_red_ratio_threshold < 0.0: + self.lucky_draw_red_ratio_threshold = 0.0 + if self.lucky_draw_red_ratio_threshold > 1.0: + self.lucky_draw_red_ratio_threshold = 1.0 self.live_room_match_threshold = _float( "live_room_match_threshold", self.live_room_match_threshold, @@ -280,7 +298,18 @@ class fudai_analyse: """读取像素阶段状态(用于阶段诊断)。""" import os pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") - return douyin_pixel.read_pixel_stage_state_from_screenshot(pic_path) + # 获取分辨率比例和y偏移参数 + resolution_ratio_x = int(getattr(self, "resolution_ratio_x", 1080) or 1080) + resolution_ratio_y = int(getattr(self, "resolution_ratio_y", 2400) or 2400) + y_pianyi = int(getattr(self, "y_pianyi", 0) or 0) + lucky_threshold = float(getattr(self, "lucky_draw_red_ratio_threshold", 0.9) or 0.9) + return douyin_pixel.read_pixel_stage_state_from_screenshot( + pic_path, + resolution_ratio_x, + resolution_ratio_y, + y_pianyi, + lucky_threshold, + ) def _check_in_live_room_by_icon(self) -> Tuple[bool, float]: """通过右上角关闭/心形图标进行直播间图形识别(轻量模板匹配版)。 diff --git a/douyin_fudai_core.py b/douyin_fudai_core.py index 8e76453..8d6d3a8 100644 --- a/douyin_fudai_core.py +++ b/douyin_fudai_core.py @@ -149,11 +149,11 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo def check_contain(analyser, contains: str = "") -> bool: - """检查福袋内容是否是想要,从配置文件 config 中读取。 + """检查福袋内容是否命中“黑名单”关键词(只保留黑名单逻辑,不再使用白名单)。 - 返回值语义与原版保持一致: - - True : “建议丢弃”(内容不是想要的 / 未明确是否想要) - - False : “可以保留”(内容是想要的,或凌晨时段不做内容过滤) + 返回值语义(调整后): + - True : “建议丢弃”(内容命中黑名单 contains_not_want) + - False : “可以保留”(未命中黑名单,或凌晨时段不做内容过滤) """ try: hour = int(analyser.operation.get_current_hour()) @@ -169,27 +169,19 @@ def check_contain(analyser, contains: str = "") -> bool: return False try: - for contain in getattr(analyser, "contains_want", []) or []: - if contain and contain in (contains or ""): - try: - analyser._log_kv("筛选", "福袋内容是想要的", keyword=contain, contains=contains[:80] if contains else "") - except Exception: - pass - return False - for contain in getattr(analyser, "contains_not_want", []) or []: if contain and contain in (contains or ""): try: - analyser._log_kv("筛选", "福袋内容不是想要的", keyword=contain, contains=contains[:80] if contains else "") + analyser._log_kv("筛选", "福袋内容命中黑名单,将丢弃", keyword=contain, contains=contains[:80] if contains else "") except Exception: pass return True try: - analyser._log_kv("筛选", "福袋内容未明确是否想要", contains=contains[:80] if contains else "") + analyser._log_kv("筛选", "福袋内容未命中黑名单,保留", contains=contains[:80] if contains else "") except Exception: pass - return True + return False except Exception: # 容错:异常时不过滤 try: @@ -217,6 +209,22 @@ def attend_choujiang(analyser) -> bool: analyser.click(500, 470) # 点击刚才打开福袋的旁边位置 analyser._log_kv("参与", "关闭福袋详情", action="关闭详情") return True + elif ("活动已结束" in attend_button_text) or ("活动己结束" in attend_button_text): + # 活动结束:按一次返回键退出详情 + analyser.last_attend_fail_reason = "activity_ended" + try: + analyser._log_kv("参与", "活动已结束:按返回键退出详情", result="activity_ended") + except Exception: + pass + try: + analyser.operation.click_back(analyser.device_id) + analyser.operation.delay(0.5) + except Exception: + try: + analyser.click(500, 470) + except Exception: + pass + return False elif "还需看播" in attend_button_text: # 如果识别到需要看播 analyser.last_attend_fail_reason = "watch_required" analyser._log_kv("参与", "需要看播时长:默认不参与", result="看播门槛") diff --git a/douyin_fudai_detail.py b/douyin_fudai_detail.py index fde66bc..62c4250 100644 --- a/douyin_fudai_detail.py +++ b/douyin_fudai_detail.py @@ -51,8 +51,11 @@ def ensure_fudai_detail_open(analyser: Any) -> bool: def _is_wrong_coupon_popup(analyser: Any) -> bool: """在已点击疑似福袋后,判断当前弹窗是否为优惠券类,而非真正福袋详情。 - 只在“点击详情后”调用,不在平时循环中使用,避免额外开销。 - 逻辑:对屏幕中部区域做颜色统计,若橙券像素明显多于粉袋像素,则视为优惠券弹窗。 + 只在"点击详情后"调用,不在平时循环中使用,避免额外开销。 + 逻辑: + 1. 对屏幕中部区域做颜色统计 + 2. 如果同时检测到福袋详情和优惠券特征,需要OCR确认"开心收下"字样 + 3. 只有OCR确认是"开心收下"时,才判定为优惠券弹窗 """ try: analyser.operation.get_screenshot(analyser.device_id) @@ -109,8 +112,51 @@ def _is_wrong_coupon_popup(analyser: Any) -> bool: except Exception: pass - # 券像素明显多于粉袋像素,则认为是优惠券弹窗 - return coupon_like > fudai_like * 1.2 + # 如果券像素明显多于粉袋像素,可能需要OCR确认 + is_coupon_like_by_color = coupon_like > fudai_like * 1.2 + + # 检测是否同时有福袋详情特征(通过像素检测) + has_fudai_detail = False + try: + import douyin_pixel + resolution_ratio_x = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + resolution_ratio_y = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0) + pic_rgb = pic.convert("RGB") + has_fudai_detail = douyin_pixel.detect_fudai_detail_page(pic_rgb, resolution_ratio_x, resolution_ratio_y, y_pianyi) + except Exception: + pass + + # 如果颜色统计显示可能是优惠券,但同时也检测到福袋详情,需要OCR确认 + if is_coupon_like_by_color and has_fudai_detail: + try: + analyser._log_kv("弹窗", "颜色统计显示可能是优惠券,但检测到福袋详情,需要OCR确认") + # 使用参与按钮区域检测"开心收下" + analyser.cut_pic(200, 1940, 880, 2140, "", "参与按钮") + coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "") + + # 如果模式0未识别到,尝试模式1 + enable_ocr_mode1 = bool(getattr(analyser, "enable_ocr_mode1", False)) + if enable_ocr_mode1 and (not coupon_text or "开心收下" not in coupon_text): + coupon_text = str(analyser.operation.analyse_pic_word("参与按钮", 1) or "") + + if coupon_text and "开心收下" in coupon_text: + analyser._log_kv("弹窗", "OCR确认:检测到'开心收下',判定为优惠券弹窗", OCR文本=coupon_text[:50]) + return True + else: + analyser._log_kv("弹窗", "OCR确认:未检测到'开心收下',判定为福袋详情页", OCR文本=coupon_text[:50] if coupon_text else "空") + return False + except Exception as e: + # OCR确认失败,如果颜色统计明显偏向优惠券,则按颜色统计结果 + analyser._log_kv("弹窗", "OCR确认失败,按颜色统计结果", error=str(e)) + return is_coupon_like_by_color + + # 如果颜色统计显示可能是优惠券,且未检测到福袋详情,直接判定为优惠券弹窗 + if is_coupon_like_by_color: + return True + + # 否则判定为福袋详情页 + return False def read_live_room_title_core( diff --git a/douyin_pixel.py b/douyin_pixel.py index 4abf9bb..6a568df 100644 --- a/douyin_pixel.py +++ b/douyin_pixel.py @@ -16,106 +16,113 @@ def _safe_open_screenshot_rgb(pic_path: str) -> Image.Image | None: def detect_coupon_popup_background(pic_rgb: Image.Image) -> bool: - """底部优惠券大弹窗背景(粉/红)像素快速检测。""" + """检测底部优惠券大弹窗(仅模板匹配)。 + + 模板匹配区域(基于1080x2400基准): + - 左上: (9, 1173) + - 右下: (1079, 2255) + 使用 `assets/coupon.png` 作为模板。 + """ try: + try: + import cv2 # type: ignore + import numpy as np # type: ignore + except Exception: + return False + width, height = pic_rgb.size - check_y_base = int(height * 0.5) - check_points = [ - (width // 2, height - 200), # 底部中心(按钮区域) - (width // 2, height - 400), # 底部中心偏上(标题区域) - (width // 3, height - 300), # 左侧 - (width * 2 // 3, height - 300), # 右侧 - (width // 2, check_y_base), # 屏幕中部(弹窗可能延伸到这里) - ] - pink_red_count = 0 - for x, y in check_points: - if 0 <= x < width and 0 <= y < height: - r, g, b = pic_rgb.getpixel((x, y)) - # 与原逻辑一致:R 值较高且明显偏红 - if r > 180 and (r - g) > 50 and (r - b) > 50: - pink_red_count += 1 - return pink_red_count >= 2 + scale_x = width / 1080.0 + scale_y = height / 2400.0 + + x1 = int(9 * scale_x) + y1 = int(1173 * scale_y) + x2 = int(1079 * scale_x) + y2 = int(2255 * scale_y) + + x1 = max(0, min(x1, width)) + y1 = max(0, min(y1, height)) + x2 = max(0, min(x2, width)) + y2 = max(0, min(y2, height)) + + if x1 >= x2 or y1 >= y2: + return False + + bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR) + roi = bgr[y1:y2, x1:x2] + if roi.size == 0: + return False + + base_dir = os.path.dirname(__file__) + template_path = os.path.join(base_dir, "assets", "coupon.png") + if not os.path.exists(template_path): + return False + + template = cv2.imread(template_path, cv2.IMREAD_COLOR) + if template is None: + return False + if roi.shape[0] < template.shape[0] or roi.shape[1] < template.shape[1]: + return False + + res = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED) + _, max_val, _, _ = cv2.minMaxLoc(res) + return max_val >= 0.75 except Exception: return False def detect_redpacket_popup_background(pic_rgb: Image.Image) -> bool: - """中央购物红包弹窗背景(红色信封 + 黄色按钮)像素快速检测。""" - try: - width, height = pic_rgb.size - center_x = width // 2 - center_y = height // 2 - check_points = [ - (center_x, center_y), # 屏幕正中心 - (center_x, center_y - 200), # 中心偏上(信封顶部) - (center_x, center_y + 200), # 中心偏下(信封底部) - (center_x - 150, center_y), # 中心偏左 - (center_x + 150, center_y), # 中心偏右 - ] - red_count = 0 - yellow_count = 0 - for x, y in check_points: - if 0 <= x < width and 0 <= y < height: - r, g, b = pic_rgb.getpixel((x, y)) - if r > 200 and g < 100 and b < 100: - red_count += 1 - if r > 200 and g > 200 and b < 150: - yellow_count += 1 - return (red_count >= 2) or (yellow_count >= 1) - except Exception: - return False + """中央购物红包弹窗检测(暂时禁用,始终返回 False)。""" + return False -def detect_lucky_draw_result_popup(pic_rgb: Image.Image) -> bool: - """检测抽奖结果弹窗:大片红色背景 + 中间有"我知道了"按钮区域。 - - 抽奖结果弹窗通常在屏幕中下部,有大片红色背景,中间有白色/浅色的"我知道了"按钮。 - 检测区域:(380,660)-(720,755) 基准1080x2400 +def detect_lucky_draw_result_popup(pic_rgb: Image.Image, red_ratio_threshold: float = 0.3) -> bool: + """检测抽奖结果弹窗:检测指定区域的红色占比。 + + 使用基准 1080x2400 坐标的检测区域: + - 左上: (175, 1258) + - 右下: (897, 1389) """ try: width, height = pic_rgb.size - # 缩放坐标到实际尺寸 scale_x = width / 1080.0 scale_y = height / 2400.0 - - # 检测区域(基准1080x2400) - x1 = int(380 * scale_x) - y1 = int(660 * scale_y) - x2 = int(720 * scale_x) - y2 = int(755 * scale_y) - - # 确保坐标在范围内 - x1 = max(0, min(x1, width)) - y1 = max(0, min(y1, height)) - x2 = max(0, min(x2, width)) - y2 = max(0, min(y2, height)) - + + x1 = int(175 * scale_x) + y1 = int(1258 * scale_y) + x2 = int(897 * scale_x) + y2 = int(1389 * scale_y) + + # 边界与顺序 + x1, x2 = max(0, min(x1, width)), max(0, min(x2, width)) + y1, y2 = max(0, min(y1, height)), max(0, min(y2, height)) + if x1 > x2: + x1, x2 = x2, x1 + if y1 > y2: + y1, y2 = y2, y1 + if x1 >= x2 or y1 >= y2: return False - - # 采样检测点:检测大片红色区域 + red_count = 0 - sample_points = [] + total_samples = 0 step_x = max(1, (x2 - x1) // 10) step_y = max(1, (y2 - y1) // 10) - + for y in range(y1, y2, step_y): for x in range(x1, x2, step_x): try: r, g, b = pic_rgb.getpixel((x, y)) - # 检测红色:R值高,G和B相对较低 + total_samples += 1 if r > 200 and (r - g) > 50 and (r - b) > 50: red_count += 1 except Exception: continue - - # 如果红色像素占比足够高(至少30%),认为有大片红色背景 - total_samples = len(list(range(y1, y2, step_y))) * len(list(range(x1, x2, step_x))) + if total_samples == 0: return False - - red_ratio = red_count / total_samples if total_samples > 0 else 0 - return red_ratio >= 0.3 + + red_ratio = red_count / total_samples + return red_ratio >= red_ratio_threshold except Exception: return False @@ -306,10 +313,113 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]: return False, 0.0 -def read_pixel_stage_state_from_screenshot(pic_path: str) -> dict[str, bool]: +def detect_fudai_detail_page(pic_rgb: Image.Image, resolution_ratio_x: int = 1080, resolution_ratio_y: int = 2400, y_pianyi: int = 0) -> bool: + """检测是否处于福袋详情页。 + + 优先使用模板匹配检测标题区域(如“超级福袋”), + 区域基于 1080x2400 基准坐标:(414,1110)-(661,1176)。 + 若模板匹配不可用或模板文件缺失,则回退到旧的像素检测逻辑。 + + 参数: + pic_rgb: RGB格式的整屏截图 + resolution_ratio_x: 分辨率X比例(默认1080) + resolution_ratio_y: 分辨率Y比例(默认2400) + y_pianyi: Y轴偏移(默认0) + + 返回: + bool: 是否检测到福袋详情页 + """ + # ---------- 优先:模板匹配检测标题区域 ---------- + try: + try: + import cv2 # type: ignore + import numpy as np # type: ignore + except Exception: + cv2 = None # type: ignore + np = None # type: ignore + + if cv2 is not None and np is not None: + width, height = pic_rgb.size + # 缩放坐标到实际分辨率(基于1080x2400) + scale_x = width / 1080.0 + scale_y = height / 2400.0 + + x1 = int(414 * scale_x) + y1 = int(1110 * scale_y) + y_pianyi + x2 = int(661 * scale_x) + y2 = int(1176 * scale_y) + y_pianyi + + # 边界检查 + x1 = max(0, min(x1, width)) + y1 = max(0, min(y1, height)) + x2 = max(0, min(x2, width)) + y2 = max(0, min(y2, height)) + if x1 < x2 and y1 < y2: + # 转为 OpenCV BGR 图像 + bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR) + roi = bgr[y1:y2, x1:x2] + if roi.size > 0: + base_dir = os.path.dirname(__file__) + # 使用用户提供的超级福袋标题模板:assets/xiangqing.png + template_path = os.path.join(base_dir, "assets", "xiangqing.png") + if os.path.exists(template_path): + template = cv2.imread(template_path, cv2.IMREAD_COLOR) + if template is not None and roi.shape[0] >= template.shape[0] and roi.shape[1] >= template.shape[1]: + res = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED) + min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) + # 固定阈值 0.7,后续如需可抽到配置 + if max_val >= 0.7: + return True + except Exception: + # 模板匹配异常时,不抛出,回退到像素检测 + pass + + # ---------- 回退:旧的像素颜色检测 ---------- + try: + width, height = pic_rgb.size + + # 检测参与按钮附近的特定颜色(兼容旧逻辑) + x = 536 * resolution_ratio_x // 1080 + if not (0 <= x < width): + return False + + base_ys = (883, 983, 1058) + offsets = (0, y_pianyi, -y_pianyi) + + for base_y in base_ys: + y0 = base_y * resolution_ratio_y // 2400 + for dy in offsets: + y = y0 + dy + if not (0 <= y < height): + continue + try: + r, g, b = pic_rgb.getpixel((x, y)) + if 30 <= r <= 38 and 34 <= g <= 40 and 78 <= b <= 84: + return True + except Exception: + continue + except Exception: + pass + + return False + + +def read_pixel_stage_state_from_screenshot( + pic_path: str, + resolution_ratio_x: int = 1080, + resolution_ratio_y: int = 2400, + y_pianyi: int = 0, + lucky_draw_red_ratio_threshold: float = 0.3, +) -> dict[str, bool]: """从 screenshot.png 读取"阶段诊断"需要的多区域像素特征(不调用 OCR)。 使用多线程并行执行所有检测函数以提高性能。 + + 参数: + pic_path: 截图路径 + resolution_ratio_x: 分辨率X比例(默认1080) + resolution_ratio_y: 分辨率Y比例(默认2400) + y_pianyi: Y轴偏移(默认0) """ state: dict[str, bool] = { "has_coupon_bg": False, @@ -317,22 +427,25 @@ def read_pixel_stage_state_from_screenshot(pic_path: str) -> dict[str, bool]: "has_lucky_draw_result": False, "has_attend_button_red": False, "has_fansclub_join_red": False, + "has_fudai_detail": False, } pic_rgb = _safe_open_screenshot_rgb(pic_path) if pic_rgb is None: return state # 并行执行所有检测函数 + # 注意:福袋详情检测需要额外参数,使用lambda包装 detection_tasks = { "has_coupon_bg": detect_coupon_popup_background, "has_redpacket_bg": detect_redpacket_popup_background, - "has_lucky_draw_result": detect_lucky_draw_result_popup, + "has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup(pic, lucky_draw_red_ratio_threshold), "has_attend_button_red": detect_attend_button_red_area, "has_fansclub_join_red": detect_fansclub_join_red_area, + "has_fudai_detail": lambda pic: detect_fudai_detail_page(pic, resolution_ratio_x, resolution_ratio_y, y_pianyi), } # 使用线程池并行执行检测 - with ThreadPoolExecutor(max_workers=5) as executor: + with ThreadPoolExecutor(max_workers=6) as executor: # 提交所有任务 future_to_key = { executor.submit(detect_func, pic_rgb): key diff --git a/douyin_popups.py b/douyin_popups.py index 754afb3..c968adc 100644 --- a/douyin_popups.py +++ b/douyin_popups.py @@ -8,182 +8,30 @@ import douyin_pixel def check_coupon_popup(analyser) -> bool: - """從 `douyin_fudai.fudai_analyse._check_coupon_popup` 抽離。 - - 像素優先,OCR 僅作補充且不推翻像素結論。 - analyser 需提供: - - cut_pic(...) - - operation.analyse_pic_word(...) - - _log_kv(...) - """ + """优惠券弹窗检测(仅模板匹配,使用 assets/coupon.png)。""" check_start = time.time() - - # 步驟0:快速像素檢測彈窗背景(粉色/紅色區域) - pixel_check_start = time.time() - has_popup_background = False try: pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") pic = Image.open(pic_path).convert("RGB") - has_popup_background = bool(douyin_pixel.detect_coupon_popup_background(pic)) - _ = time.time() - pixel_check_start - if not has_popup_background: - return False - except Exception: - _ = time.time() - pixel_check_start - has_popup_background = False - - # 步驟1:截圖標題區域 - cut_title_start = time.time() - try: - analyser.cut_pic(60, 1260, 1020, 1480, "", "診斷優惠券標題") - cut_title_elapsed = time.time() - cut_title_start + matched = bool(douyin_pixel.detect_coupon_popup_background(pic)) except Exception as e: - cut_title_elapsed = time.time() - cut_title_start - analyser._log_kv("彈窗檢測步驟", "優惠券-截圖標題區域失敗", error=str(e), 耗時秒=f"{cut_title_elapsed:.3f}") - return False - - # 步驟2:OCR 標題(模式0) - ocr_title0_start = time.time() - try: - t1 = str(analyser.operation.analyse_pic_word("診斷優惠券標題", 0) or "") - ocr_title0_elapsed = time.time() - ocr_title0_start - except Exception as e: - t1 = "" - ocr_title0_elapsed = time.time() - ocr_title0_start - analyser._log_kv("彈窗檢測步驟", "優惠券-OCR標題區域(模式0)失敗", error=str(e), 耗時秒=f"{ocr_title0_elapsed:.3f}") - - # 步驟3:模式1(僅在模式0為空時) - ocr_title1_elapsed = 0.0 - if not t1: - ocr_title1_start = time.time() try: - t1 = str(analyser.operation.analyse_pic_word("診斷優惠券標題", 1) or "") - ocr_title1_elapsed = time.time() - ocr_title1_start - except Exception as e: - ocr_title1_elapsed = time.time() - ocr_title1_start - analyser._log_kv("彈窗檢測步驟", "優惠券-OCR標題區域(模式1)失敗", error=str(e), 耗時秒=f"{ocr_title1_elapsed:.3f}") - - if not t1: - if has_popup_background: - total_elapsed = time.time() - check_start - analyser._log_kv( - "彈窗檢測步驟", - "優惠券-標題OCR為空但像素判定有彈窗,按像素結果返回", - 總耗時秒=f"{total_elapsed:.3f}", - 截圖耗時秒=f"{cut_title_elapsed:.3f}", - 像素判定="有彈窗背景", - ) - return True + analyser._log_kv("彈窗檢測步驟", "優惠券-讀取截圖失敗", error=str(e)) + except Exception: + pass return False - strong_keywords_title = ("購物券", "新客", "專享券") - if any(kw in t1 for kw in strong_keywords_title): - total_elapsed = time.time() - check_start - matched_strong = [kw for kw in strong_keywords_title if kw in t1] - analyser._log_kv( - "彈窗檢測步驟", - "優惠券-標題區域檢測到強關鍵詞,快速返回", - 匹配到的強關鍵詞=matched_strong, - 識別文本=t1[:50], - 總耗時秒=f"{total_elapsed:.3f}", - 截圖耗時秒=f"{cut_title_elapsed:.3f}", - OCR耗時秒=f"{(ocr_title0_elapsed + ocr_title1_elapsed):.3f}", - 節省="跳過按鈕檢測", - ) - return True - - import re - - t1_stripped = t1.strip() - possible_chars = ("券", "新", "客", "購", "物", "專", "享", "領", "取", "收", "下", "一", "得", "元", "分鐘") - if not any(char in t1_stripped for char in possible_chars): - return False - - t1_clean = re.sub(r"[\s\d\W]", "", t1_stripped) - if len(t1_clean) < 2: - if has_popup_background: - total_elapsed = time.time() - check_start - analyser._log_kv( - "彈窗檢測步驟", - "優惠券-標題文本過短但像素判定有彈窗,按像素結果返回", - 總耗時秒=f"{total_elapsed:.3f}", - 截圖耗時秒=f"{cut_title_elapsed:.3f}", - 像素判定="有彈窗背景", - 標題文本=t1[:50], - ) - return True - return False - - # 步驟4:截圖按鈕區域 - cut_btn_start = time.time() - try: - analyser.cut_pic(260, 2080, 820, 2240, "", "診斷優惠券按鈕") - cut_btn_elapsed = time.time() - cut_btn_start - except Exception as e: - cut_btn_elapsed = time.time() - cut_btn_start - analyser._log_kv("彈窗檢測步驟", "優惠券-截圖按鈕區域失敗", error=str(e), 耗時秒=f"{cut_btn_elapsed:.3f}") - cut_btn_elapsed = 0.0 - - # 步驟5:OCR 按鈕(模式0) - ocr_btn0_start = time.time() - try: - t2 = str(analyser.operation.analyse_pic_word("診斷優惠券按鈕", 0) or "") - ocr_btn0_elapsed = time.time() - ocr_btn0_start - except Exception as e: - t2 = "" - ocr_btn0_elapsed = time.time() - ocr_btn0_start - analyser._log_kv("彈窗檢測步驟", "優惠券-OCR按鈕區域(模式0)失敗", error=str(e), 耗時秒=f"{ocr_btn0_elapsed:.3f}") - - # 步驟6:模式1(僅在模式0為空時) - ocr_btn1_elapsed = 0.0 - if not t2: - ocr_btn1_start = time.time() - try: - t2 = str(analyser.operation.analyse_pic_word("診斷優惠券按鈕", 1) or "") - ocr_btn1_elapsed = time.time() - ocr_btn1_start - except Exception as e: - ocr_btn1_elapsed = time.time() - ocr_btn1_start - analyser._log_kv("彈窗檢測步驟", "優惠券-OCR按鈕區域(模式1)失敗", error=str(e), 耗時秒=f"{ocr_btn1_elapsed:.3f}") - - hay = (t1 + " " + t2).strip() - if not hay: - if has_popup_background: - total_elapsed = time.time() - check_start - analyser._log_kv( - "彈窗檢測步驟", - "優惠券-OCR標題和按鈕均為空,但像素判定有彈窗,按像素結果返回", - 總耗時秒=f"{total_elapsed:.3f}", - 像素判定="有彈窗背景", - ) - return True - return False - - strong_keywords = ("購物券", "新客", "專享券") - weak_keywords = ("領取", "收下", "開心收下") - has_strong_keyword = any(kw in hay for kw in strong_keywords) - has_weak_keyword = any(kw in hay for kw in weak_keywords) - has_coupon_keyword = ("券" in hay) or ("新客" in hay) or ("購物券" in hay) - - result = has_strong_keyword or (has_weak_keyword and has_coupon_keyword) - if not result and has_popup_background: - result = True - total_elapsed = time.time() - check_start - ocr_total = ocr_title0_elapsed + ocr_title1_elapsed + ocr_btn0_elapsed + ocr_btn1_elapsed - if result: - matched_keys = [kw for kw in strong_keywords if kw in hay] + [kw for kw in weak_keywords if kw in hay] - analyser._log_kv("彈窗檢測步驟", "優惠券-檢測到彈窗", 匹配到的關鍵詞=matched_keys, 總耗時秒=f"{total_elapsed:.3f}", OCR耗時秒=f"{ocr_total:.3f}") - else: - matched_keys = [kw for kw in strong_keywords if kw in hay] + [kw for kw in weak_keywords if kw in hay] + try: analyser._log_kv( "彈窗檢測步驟", - "優惠券-未檢測到彈窗", - 合併文本=hay[:100] if hay else "空", - 匹配到的關鍵詞=matched_keys if matched_keys else [], + "優惠券-模板匹配結果", + matched=int(bool(matched)), 總耗時秒=f"{total_elapsed:.3f}", - OCR耗時秒=f"{ocr_total:.3f}", ) - return result + except Exception: + pass + return matched def check_shopping_redpacket_popup(analyser) -> bool: diff --git a/douyin_stage.py b/douyin_stage.py index 50d98a3..61b3270 100644 --- a/douyin_stage.py +++ b/douyin_stage.py @@ -304,6 +304,7 @@ def diagnose_stage_from_current_screen(self): 抽奖结果弹窗=bool(pixel_state.get("has_lucky_draw_result", False)), 参与按钮红色区域=bool(pixel_state.get("has_attend_button_red", False)), 粉丝团加入红色区域=bool(pixel_state.get("has_fansclub_join_red", False)), + 福袋详情页=bool(pixel_state.get("has_fudai_detail", False)), ) except Exception as e: import traceback @@ -581,22 +582,29 @@ def diagnose_stage_from_current_screen(self): ) # 不返回任何阶段,继续后续检测 - # ========== 步骤1:像素检测福袋详情页(补充检测)========== - # 如果像素检测未命中,再用这个方法检测 + # ========== 步骤1:像素检测福袋详情页(已合并到并行检测中)========== + # 优先使用并行检测的结果 + detail_detected = pixel_state.get("has_fudai_detail", False) + if detail_detected: + total_elapsed = (time.time() - diag_start) * 1000 + _log("步骤1[像素检测福袋详情]-命中(并行检测)", 总耗时毫秒=total_elapsed) + _log("阶段诊断完成(像素检测)", 阶段="FUDai_DETAIL", 原因="福袋详情页像素检测(并行)") + return "FUDai_DETAIL", "像素检测确认(福袋详情页,并行检测)" + + # 如果并行检测未命中,使用完整检测方法(包含OCR兜底)作为补充 step_start = time.time() - _log("步骤1[像素检测福袋详情]-开始", 说明="补充检测") - detail_detected = False + _log("步骤1[像素检测福袋详情]-并行检测未命中,使用完整检测方法补充", 说明="补充检测") try: check_result = self.check_in_fudai_detail() elapsed = (time.time() - step_start) * 1000 total_elapsed = (time.time() - diag_start) * 1000 if check_result: detail_detected = True - _log("步骤1[像素检测福袋详情]-命中", 耗时毫秒=elapsed, 总耗时毫秒=total_elapsed) - _log("阶段诊断完成(像素检测)", 阶段="FUDai_DETAIL", 原因="福袋详情页像素检测") - return "FUDai_DETAIL", "像素检测确认(福袋详情页)" + _log("步骤1[像素检测福袋详情]-命中(完整检测)", 耗时毫秒=elapsed, 总耗时毫秒=total_elapsed) + _log("阶段诊断完成(完整检测)", 阶段="FUDai_DETAIL", 原因="福袋详情页完整检测") + return "FUDai_DETAIL", "完整检测确认(福袋详情页)" else: - _log("步骤1[像素检测福袋详情]-未命中", 耗时毫秒=elapsed) + _log("步骤1[像素检测福袋详情]-未命中(完整检测)", 耗时毫秒=elapsed) except Exception as e: import traceback elapsed = (time.time() - step_start) * 1000 diff --git a/gui_app.py b/gui_app.py index 39d0d73..6643823 100644 --- a/gui_app.py +++ b/gui_app.py @@ -182,6 +182,8 @@ def main(): enable_ocr_mode1_var = tk.BooleanVar(value=bool(cfg.get("enable_ocr_mode1", False))) # 福袋模板匹配阈值 fudai_template_match_threshold_var = tk.DoubleVar(value=float(cfg.get("fudai_template_match_threshold", 0.7) or 0.7)) + # 开奖页面红色占比阈值(0.0~1.0,默认0.9) + lucky_draw_red_ratio_threshold_var = tk.DoubleVar(value=float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)) run_box = ttk.LabelFrame(left, text="运行设置") run_box.pack(fill=X, pady=(0, 10)) @@ -445,14 +447,16 @@ def main(): ttk.Spinbox(diag_time_r3, from_=0.0, to=1.0, increment=0.01, textvariable=fudai_template_match_threshold_var, width=8).pack(side=LEFT) ttk.Label(diag_time_r3, text="(0.0-1.0,彩色匹配)").pack(side=LEFT, padx=(6, 0)) - kw_box = ttk.LabelFrame(left, text="关键词(每行一个)") + diag_time_r4 = ttk.Frame(diag_time_box) + diag_time_r4.pack(fill=X, padx=10, pady=(0, 10)) + ttk.Label(diag_time_r4, text="开奖页红色占比阈值:").pack(side=LEFT) + ttk.Spinbox(diag_time_r4, from_=0.0, to=1.0, increment=0.01, textvariable=lucky_draw_red_ratio_threshold_var, width=8).pack(side=LEFT) + ttk.Label(diag_time_r4, text="(默认0.90,≥此占比判定开奖页)").pack(side=LEFT, padx=(6, 0)) + + kw_box = ttk.LabelFrame(left, text="关键词(每行一个,仅黑名单)") kw_box.pack(fill=BOTH, expand=True) - ttk.Label(kw_box, text="想要 contains_want").pack(anchor="w", padx=10, pady=(8, 4)) - want_text = ScrolledText(kw_box, height=8) - want_text.pack(fill=X, padx=10) - - ttk.Label(kw_box, text="不想要 contains_not_want").pack(anchor="w", padx=10, pady=(10, 4)) + ttk.Label(kw_box, text="不想要 contains_not_want(黑名单)").pack(anchor="w", padx=10, pady=(10, 4)) not_want_text = ScrolledText(kw_box, height=8) not_want_text.pack(fill=X, padx=10, pady=(0, 10)) @@ -473,6 +477,7 @@ def main(): reset_after_swipes_var.set(int(cfg.get("reset_after_swipes", 10) or 10)) auto_join_var.set(bool(cfg.get("auto_join_fansclub", False))) fansclub_action_var.set(str(cfg.get("fansclub_fail_action", "stay") or "stay").lower()) + lucky_draw_red_ratio_threshold_var.set(float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)) # Web端新增配置 - 高价值预约相关 high_value_fudai_enabled_var.set(bool(cfg.get("high_value_fudai_enabled", False))) @@ -525,13 +530,11 @@ def main(): yg_comment_close_x_var.set(int(cfg.get("yanghao_comment_close_x", 0) or 0)) yg_comment_close_y_var.set(int(cfg.get("yanghao_comment_close_y", 0) or 0)) - want = cfg.get("contains_want", []) or [] + # 仅保留黑名单 contains_not_want not_want = cfg.get("contains_not_want", []) or [] yg_comment_texts_list = cfg.get("yanghao_comment_texts", []) or [] yg_like_keywords_list = cfg.get("yanghao_like_keywords", []) or [] yg_fav_keywords_list = cfg.get("yanghao_fav_keywords", []) or [] - want_text.delete("1.0", "end") - want_text.insert("1.0", "\n".join(want)) not_want_text.delete("1.0", "end") not_want_text.insert("1.0", "\n".join(not_want)) yg_comment_texts.delete("1.0", "end") @@ -542,7 +545,7 @@ def main(): yg_fav_keywords_text.insert("1.0", "\n".join(yg_fav_keywords_list)) def save_ui_to_config(): - want_lines = [x.strip() for x in want_text.get("1.0", "end").splitlines() if x.strip()] + # 仅保存黑名单 contains_not_want not_want_lines = [x.strip() for x in not_want_text.get("1.0", "end").splitlines() if x.strip()] yg_comment_text_lines = [x.strip() for x in yg_comment_texts.get("1.0", "end").splitlines() if x.strip()] yg_like_kw_lines = [x.strip() for x in yg_like_keywords_text.get("1.0", "end").splitlines() if x.strip()] @@ -551,7 +554,6 @@ def main(): cfg2 = read_config() cfg2["needswitch"] = bool(needswitch_var.get()) cfg2["wait_minutes"] = int(wait_minutes_var.get() or 5) - cfg2["contains_want"] = want_lines cfg2["contains_not_want"] = not_want_lines cfg2["min_prize_value_yuan"] = float(min_value_var.get() or 0) cfg2["min_participants"] = int(min_participants_var.get() or 0) @@ -561,6 +563,7 @@ def main(): cfg2["reset_after_swipes"] = int(reset_after_swipes_var.get() or 10) cfg2["auto_join_fansclub"] = bool(auto_join_var.get()) cfg2["fansclub_fail_action"] = str(fansclub_action_var.get() or "stay").lower() + cfg2["lucky_draw_red_ratio_threshold"] = float(lucky_draw_red_ratio_threshold_var.get() or 0.9) # Web端新增配置 - 高价值预约相关 cfg2["high_value_fudai_enabled"] = bool(high_value_fudai_enabled_var.get()) @@ -624,10 +627,19 @@ def main(): load_config_to_ui() - btns = ttk.Frame(left) - btns.pack(fill=X, pady=(10, 0)) - ttk.Button(btns, text="加载配置", command=load_config_to_ui).pack(side=LEFT, padx=(0, 8)) - ttk.Button(btns, text="保存配置", command=save_ui_to_config).pack(side=LEFT, padx=(0, 8)) + # 顶部常驻按钮区域(与设备选择同一行,不随左侧滚动) + top_btns = ttk.Frame(top) + top_btns.pack(side=RIGHT, padx=(20, 0)) + ttk.Button(top_btns, text="保存配置", command=save_ui_to_config).pack(side=LEFT, padx=(0, 8)) + # 截图+OCR 按钮也放在顶部,方便随时使用 + # 具体回调在后文定义,这里先占位,通过 lambda 延迟绑定 + screenshot_button_var = {"command": None} + def _bind_screenshot_button(btn): + # 在 do_screenshot 定义后调用,将真正的 command 绑定到按钮 + screenshot_button_var["button"] = btn + screenshot_btn = ttk.Button(top_btns, text="截图+OCR") + screenshot_btn.pack(side=LEFT, padx=(0, 8)) + _bind_screenshot_button(screenshot_btn) # OCR区域配置:定义所有需要识别的区域(坐标基于1080x2400基准) OCR_REGIONS = [ @@ -768,8 +780,14 @@ def main(): thread = threading.Thread(target=screenshot_thread, daemon=True) thread.start() - - ttk.Button(btns, text="截图+OCR", command=do_screenshot).pack(side=LEFT, padx=(0, 8)) + + # 将顶部“截图+OCR”按钮的回调绑定到 do_screenshot + try: + btn = screenshot_button_var.get("button") + if btn is not None: + btn.configure(command=do_screenshot) + except Exception: + pass # 右侧:Notebook(日志 / 截图预览 / 统计信息 / 预约队列 / 高价值房间) notebook = ttk.Notebook(right) diff --git a/path_config.py b/path_config.py index ea66c9d..bdd2546 100644 --- a/path_config.py +++ b/path_config.py @@ -164,6 +164,9 @@ def ensure_dir(path: str) -> None: + + + diff --git a/tools/pick_coords.py b/tools/pick_coords.py index 9d11881..d6f4cef 100644 --- a/tools/pick_coords.py +++ b/tools/pick_coords.py @@ -25,6 +25,8 @@ class CoordPicker: 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() @@ -32,11 +34,17 @@ class CoordPicker: 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("", lambda e: self.open_dialog()) + self.root.bind("", lambda e: self.prev_image()) + self.root.bind("", lambda e: self.next_image()) + self.root.bind("", lambda e: self.prev_image()) # PageUp + self.root.bind("", lambda e: self.next_image()) # PageDown self.canvas = tk.Canvas(self.root, width=800, height=600) self.canvas.pack(fill=tk.BOTH, expand=False) @@ -54,14 +62,32 @@ class CoordPicker: if not self.open_dialog(): raise SystemExit(2) else: - self.set_image(image_path) + self.set_image(image_path, update_list=True) - def set_image(self, image_path: Path) -> None: + 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() @@ -101,7 +127,7 @@ class CoordPicker: if not filename: return False try: - self.set_image(Path(filename)) + self.set_image(Path(filename), update_list=True) return True except Exception as e: self.status.set(f"打开失败: {e}") @@ -129,6 +155,28 @@ class CoordPicker: 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()