Home Assistant Unofficial Reference 2024.12.1
pil.py
Go to the documentation of this file.
1 """PIL utilities.
2 
3 Can only be used by integrations that have pillow in their requirements.
4 """
5 
6 from __future__ import annotations
7 
8 from PIL.ImageDraw import ImageDraw
9 
10 
12  draw: ImageDraw,
13  box: tuple[float, float, float, float],
14  img_width: int,
15  img_height: int,
16  text: str = "",
17  color: tuple[int, int, int] = (255, 255, 0),
18 ) -> None:
19  """Draw a bounding box on and image.
20 
21  The bounding box is defined by the tuple (y_min, x_min, y_max, x_max)
22  where the coordinates are floats in the range [0.0, 1.0] and
23  relative to the width and height of the image.
24 
25  For example, if an image is 100 x 200 pixels (height x width) and the bounding
26  box is `(0.1, 0.2, 0.5, 0.9)`, the upper-left and bottom-right coordinates of
27  the bounding box will be `(40, 10)` to `(180, 50)` (in (x,y) coordinates).
28  """
29 
30  line_width = 3
31  font_height = 20
32  y_min, x_min, y_max, x_max = box
33  (left, right, top, bottom) = (
34  x_min * img_width,
35  x_max * img_width,
36  y_min * img_height,
37  y_max * img_height,
38  )
39  draw.line(
40  [(left, top), (left, bottom), (right, bottom), (right, top), (left, top)],
41  width=line_width,
42  fill=color,
43  )
44  if text:
45  draw.text(
46  (left + line_width, abs(top - line_width - font_height)),
47  text,
48  fill=color,
49  font_size=font_height,
50  )
None draw_box(ImageDraw draw, tuple[float, float, float, float] box, int img_width, int img_height, str text="", tuple[int, int, int] color=(255, 255, 0))
Definition: pil.py:18