def mask_overlay(img, mask, color, expand=-1):
if expand > 0:
kernel = np.ones((expand, expand), np.uint8) ## only expand on y direction to remove shadow
mask_ext = cv2.dilate(mask, kernel, iterations=1)
else:
mask_ext = mask
mask_bool = mask_ext > 0
img[mask_bool] = color
def show_masks(img, masks, borders=True):
## input a list of masks, and show the masks in different color, overlays on the original image
if len(masks) == 0:
return
mask_vis = np.ones((masks.shape[1], masks.shape[2], 3), dtype=np.uint8)
for i in range(masks.shape[0]):
mask = masks[i].astype(bool)
color_mask = np.random.randint(0, 256, size=3, dtype=np.uint8)
mask_vis[mask] = color_mask
if borders:
contours, _ = cv2.findContours(mask.astype(np.uint8),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# Try to smooth contours
contours = [cv2.approxPolyDP(contour, epsilon=0.01, closed=True) for contour in contours]
# print(contours)
# cv2.drawContours(mask_vis, contours, -1, (0,0,1,0.4), thickness=1)
cv2.drawContours(mask_vis, contours, -1, (255,0,0), thickness=2)
alpha=0.4
overlay = cv2.addWeighted(img, 1 - alpha, mask_vis.astype('uint8'), alpha, 0)
return overlay