-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.py
32 lines (25 loc) · 1.23 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import cv2
import numpy as np
def overlay(image, mask, color, alpha, resize=None):
"""Combines image and its segmentation mask into a single image.
https://www.kaggle.com/code/purplejester/showing-samples-with-segmentation-mask-overlay
Params:
image: Training image. np.ndarray,
mask: Segmentation mask. np.ndarray,
color: Color for segmentation mask rendering. tuple[int, int, int] = (255, 0, 0)
alpha: Segmentation mask's transparency. float = 0.5,
resize: If provided, both image and its mask are resized before blending them together.
tuple[int, int] = (1024, 1024))
Returns:
image_combined: The combined image. np.ndarray
"""
color = color[::-1]
colored_mask = np.expand_dims(mask, 0).repeat(3, axis=0)
colored_mask = np.moveaxis(colored_mask, 0, -1)
masked = np.ma.MaskedArray(image, mask=colored_mask, fill_value=color)
image_overlay = masked.filled()
if resize is not None:
image = cv2.resize(image.transpose(1, 2, 0), resize)
image_overlay = cv2.resize(image_overlay.transpose(1, 2, 0), resize)
image_combined = cv2.addWeighted(image, 1 - alpha, image_overlay, alpha, 0)
return image_combined