2024-01-16 17:56:25 +01:00
|
|
|
import logging
|
2023-12-19 09:32:05 +01:00
|
|
|
import os
|
|
|
|
from typing import List
|
2023-12-19 09:35:45 +01:00
|
|
|
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
2023-12-19 10:55:25 +01:00
|
|
|
from PIL.Image import composite
|
2023-12-19 09:32:05 +01:00
|
|
|
|
2024-01-09 02:15:41 +01:00
|
|
|
from ml.element_detection import BoundBox
|
2023-12-19 09:32:05 +01:00
|
|
|
|
|
|
|
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
|
|
|
|
|
|
|
|
|
|
|
|
def show_image_with_boxes(
|
|
|
|
in_image_path: str, bounding_boxes: List[BoundBox], out_image_path: str = None
|
|
|
|
):
|
|
|
|
img = Image.open(in_image_path)
|
|
|
|
draw = ImageDraw.Draw(img)
|
|
|
|
font_path = DIR_PATH + "/assets/fonts/arial.ttf"
|
|
|
|
font = ImageFont.truetype(font_path, 25)
|
|
|
|
for i, box in enumerate(bounding_boxes):
|
|
|
|
draw.rectangle(box.get_params(), outline="red", width=2, fill=None)
|
2023-12-19 09:35:45 +01:00
|
|
|
draw.text((box.x1 + 5, box.y1 + 5), str(i + 1), fill="red", font=font)
|
2023-12-19 09:32:05 +01:00
|
|
|
if not out_image_path:
|
|
|
|
out_image_path = (
|
|
|
|
in_image_path.split(".")[0] + "_out." + in_image_path.split(".")[1]
|
|
|
|
)
|
|
|
|
img.save(out_image_path)
|
2023-12-19 09:35:45 +01:00
|
|
|
|
|
|
|
|
2023-12-19 10:55:25 +01:00
|
|
|
def blur_boxes_on_image(
|
2023-12-19 09:35:45 +01:00
|
|
|
in_image_path: str, bounding_boxes: List[BoundBox], out_image_path: str = None
|
|
|
|
):
|
|
|
|
img = Image.open(in_image_path)
|
2024-01-18 09:57:02 +01:00
|
|
|
blur_img = img.filter(ImageFilter.GaussianBlur(radius=13)) # to increase the blur, increase the radius
|
2023-12-19 10:55:25 +01:00
|
|
|
mask = Image.new("L", img.size, 255)
|
|
|
|
draw_mask = ImageDraw.Draw(mask)
|
2023-12-19 09:35:45 +01:00
|
|
|
for box in bounding_boxes:
|
|
|
|
if box.selected:
|
2023-12-19 10:55:25 +01:00
|
|
|
if box.object == "plate":
|
|
|
|
draw_mask.rectangle(box.get_params(), fill=0)
|
|
|
|
elif box.object == "face":
|
2023-12-19 10:55:55 +01:00
|
|
|
draw_mask.ellipse(box.get_params(), fill=0)
|
2023-12-19 10:55:25 +01:00
|
|
|
mask = mask.filter(ImageFilter.GaussianBlur(radius=3))
|
|
|
|
img = composite(img, blur_img, mask)
|
2023-12-19 09:35:45 +01:00
|
|
|
if not out_image_path:
|
|
|
|
out_image_path = (
|
|
|
|
in_image_path.split(".")[0] + "_blurred." + in_image_path.split(".")[1]
|
|
|
|
)
|
|
|
|
img.save(out_image_path)
|