From 6ff5af45d575d7d6662baf4329773c431f695e4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rn-Michael=20Miehe?= Date: Fri, 19 Dec 2025 19:46:55 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix=20`advent=5Fimage.py`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `get_average_color` working again - refactor `hide_text` (fail-fast) --- api/advent22_api/core/advent_image.py | 57 +++++++++++++++------------ 1 file changed, 31 insertions(+), 26 deletions(-) diff --git a/api/advent22_api/core/advent_image.py b/api/advent22_api/core/advent_image.py index 13d6dc2..56c1b49 100644 --- a/api/advent22_api/core/advent_image.py +++ b/api/advent22_api/core/advent_image.py @@ -1,4 +1,5 @@ import colorsys +import logging from dataclasses import dataclass from typing import Self, TypeAlias, cast @@ -14,6 +15,8 @@ _RGB: TypeAlias = tuple[int, int, int] _XY: TypeAlias = tuple[float, float] _Box: TypeAlias = tuple[int, int, int, int] +_logger = logging.getLogger(__name__) + @dataclass(slots=True, frozen=True) class AdventImage: @@ -83,15 +86,14 @@ class AdventImage: async def get_average_color( self, box: _Box, - ) -> tuple[int, int, int]: + ) -> _RGB: """ Durchschnittsfarbe eines rechteckigen Ausschnitts in einem Bild berechnen """ pixel_data = np.asarray(self.img.crop(box)) - print(pixel_data) - mean_color: np.ndarray = np.mean(pixel_data, axis=0) + mean_color: np.ndarray = np.mean(pixel_data, axis=(0, 1)) return cast(_RGB, tuple(mean_color.astype(int))) @@ -113,31 +115,34 @@ class AdventImage: xy=xy, text=text, font=font, anchor=anchor, **text_kwargs ) - if text_box is not None: - # Durchschnittsfarbe bestimmen - text_color = await self.get_average_color( - box=text_box, - ) + if text_box is None: + _logger.warning("Konnte Bildbereich nicht finden!") + return - # etwas heller/dunkler machen - tc_h, tc_s, tc_v = colorsys.rgb_to_hsv(*text_color) - tc_v = int((tc_v - 127) * 0.97) + 127 + # Durchschnittsfarbe bestimmen + text_color = await self.get_average_color( + box=text_box, + ) - if tc_v < 127: - tc_v += 3 + # etwas heller/dunkler machen + tc_h, tc_s, tc_v = colorsys.rgb_to_hsv(*text_color) + tc_v = int((tc_v - 127) * 0.97) + 127 - else: - tc_v -= 3 + if tc_v < 127: + tc_v += 3 - text_color = colorsys.hsv_to_rgb(tc_h, tc_s, tc_v) - text_color = tuple(int(val) for val in text_color) + else: + tc_v -= 3 - # Buchstaben verstecken - ImageDraw.Draw(self.img).text( - xy=xy, - text=text, - font=font, - fill=cast(_RGB, text_color), - anchor=anchor, - **text_kwargs, - ) + text_color = colorsys.hsv_to_rgb(tc_h, tc_s, tc_v) + text_color = tuple(int(val) for val in text_color) + + # Buchstaben verstecken + ImageDraw.Draw(self.img).text( + xy=xy, + text=text, + font=font, + fill=cast(_RGB, text_color), + anchor=anchor, + **text_kwargs, + )