|
|
import cv2
|
|
|
import numpy as np
|
|
|
|
|
|
|
|
|
def merge_masks(masks, method='max'):
|
|
|
if isinstance(masks, list):
|
|
|
masks = np.array(masks)
|
|
|
|
|
|
|
|
|
if len(masks.shape) != 3:
|
|
|
raise ValueError(
|
|
|
"Маски должны быть представлены в виде массива размерности (N, H, W)."
|
|
|
)
|
|
|
N, H, W = masks.shape
|
|
|
|
|
|
|
|
|
mask_colored = np.zeros((H, W, 3), dtype=np.uint8)
|
|
|
|
|
|
|
|
|
colors = [tuple(np.random.randint(0, 255, size=3)) for _ in range(N)]
|
|
|
|
|
|
|
|
|
unique_mask = np.zeros((H, W), dtype=np.uint8)
|
|
|
|
|
|
for i in range(N):
|
|
|
|
|
|
color_mask = np.zeros_like(mask_colored)
|
|
|
color_mask[masks[i] > 0] = colors[i]
|
|
|
|
|
|
|
|
|
mask_colored = cv2.addWeighted(mask_colored, 1, color_mask, 1, 0.0)
|
|
|
|
|
|
|
|
|
unique_mask[masks[i] > 0] = (
|
|
|
i + 1
|
|
|
)
|
|
|
|
|
|
return mask_colored, unique_mask
|
|
|
|
|
|
|
|
|
def create_mask(mask, random_color=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
h, w = mask.shape[-2:]
|
|
|
mask = mask.astype(np.uint8)
|
|
|
|
|
|
return mask
|
|
|
|