🐛 fix advent_image.py

- `get_average_color` working again
- refactor `hide_text` (fail-fast)
This commit is contained in:
Jörn-Michael Miehe 2025-12-19 19:46:55 +01:00
parent 5c865b8dbb
commit 6ff5af45d5

View file

@ -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,
)