diff --git a/douyin/detection/pixel/buttons.py b/douyin/detection/pixel/buttons.py index 8c313a5..df7867d 100644 --- a/douyin/detection/pixel/buttons.py +++ b/douyin/detection/pixel/buttons.py @@ -19,6 +19,14 @@ from typing import Any, Optional from ._common import _safe_open_screenshot_rgb +def _read_rgb_pixel(pic_rgb: Image.Image, x: int, y: int) -> tuple[int, int, int]: + pixel = pic_rgb.getpixel((x, y)) + if isinstance(pixel, tuple): + return int(pixel[0]), int(pixel[1]), int(pixel[2]) + value = int(pixel) + return value, value, value + + def detect_attend_button_red_area( pic_rgb: Image.Image, return_info: bool = False, @@ -86,7 +94,7 @@ def detect_attend_button_red_area( 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 = _read_rgb_pixel(pic_rgb, x, y) # 检测红色:R值高,G和B相对较低 if r > 200 and (r - g) > 50 and (r - b) > 50: red_count += 1 @@ -253,7 +261,7 @@ def detect_fansclub_join_red_area( 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 = _read_rgb_pixel(pic_rgb, x, y) # 检测红色:R值高,G和B相对较低 if r > 200 and (r - g) > 50 and (r - b) > 50: red_count += 1 diff --git a/tests/test_detection_pixel.py b/tests/test_detection_pixel.py index 3befb9e..9502240 100644 --- a/tests/test_detection_pixel.py +++ b/tests/test_detection_pixel.py @@ -240,11 +240,49 @@ class TestPixelButtons: params = list(sig.parameters.keys()) assert "pic_rgb" in params or len(params) >= 1 + def test_detect_attend_button_accepts_rgba_image(self): + from PIL import Image + + from douyin.detection.pixel.buttons import detect_attend_button_red_area + + img = Image.new("RGBA", (1080, 2400), (0, 0, 0, 255)) + for x in range(200, 880): + for y in range(2000, 2120): + img.putpixel((x, y), (255, 80, 120, 255)) + + detected, info = detect_attend_button_red_area( + img, + return_info=True, + red_ratio_threshold=0.25, + ) + + assert detected is True + assert info["red_ratio"] >= 0.25 + def test_detect_fansclub_join_exists(self): from douyin.detection.pixel.buttons import detect_fansclub_join_red_area assert callable(detect_fansclub_join_red_area) + def test_detect_fansclub_join_accepts_rgba_image(self): + from PIL import Image + + from douyin.detection.pixel.buttons import detect_fansclub_join_red_area + + img = Image.new("RGBA", (1080, 2400), (0, 0, 0, 255)) + for x in range(200, 880): + for y in range(1940, 2140): + img.putpixel((x, y), (255, 80, 120, 255)) + + detected, info = detect_fansclub_join_red_area( + img, + return_info=True, + red_ratio_threshold=0.25, + ) + + assert detected is True + assert info["red_ratio"] >= 0.25 + class TestPixelStage: """pixel/stage 模块测试。"""