🟡Visualize Masks on Server [Python]

This page explains how to visualize the output of masks with JavaScript and Python code, and overlay them onto original and restored images.

polygon_mask

An example of code converting a vectorized mask with "mask_type": "polygon_mask" to a raster image in Python and to an SVG in JavaScript

import numpy as np
from typing import Tuple, Union
from skimage.draw import polygon
from matplotlib.colors import hex2color


def view_box_to_shape(view_box: str) -> Tuple[int, int]:
    """Supplementary method to convert viewBox to image shape.

    :param view_box: str, view_box
    :return: tuple, image shape, (height, width)
    """
    view_box = [int(elem) for elem in view_box.split(" ")]
    return view_box[3] - view_box[1], view_box[2] - view_box[0]


def draw_multipolygons(vector_mask):
    """Function to rasterize vector polygon mask

    :return: np.ndarray, np.float32 2D mask with values in range [0, 1]
    """
    img_shape = view_box_to_shape(vector_mask["view_box"])
    canvas = np.zeros(img_shape, dtype=np.uint8)
    for feature in vector_mask["features"]:
        intensity = (
            np.uint8(feature["properties"]["intensity"] * 255)
            if feature["properties"]["intensity"]
            else 255
        )
        for polygon_object in feature["geometry"]["coordinates"]:
            external_contours = np.array(polygon_object[0])
            rr, cc = polygon(
                external_contours[:, 1], external_contours[:, 0], canvas.shape
            )
            canvas[rr, cc] += intensity
            if len(polygon_object) > 1:
                for contour in polygon_object[1:]:
                    internal_contour = np.array(contour)
                    rr, cc = polygon(
                        internal_contour[:, 1], internal_contour[:, 0], canvas.shape
                    )
                    canvas[rr, cc] -= intensity
        canvas = np.clip(canvas, 0, 255)
    return canvas

An example of code overlaying a vectorized mask with an input image

Input image Overlaid image

A file with an example mask is attached:

wrinkles_mask.json

point_mask

Code to convert a vectorized mask with "mask_type": "point_mask" to a raster image

polyline_mask

Code to convert a vectorized mask with "mask_type": "polyline_mask" to a raster image

Please pay attention to the lines; they should have a defined line width to be visible, so there is one additional parameter for the function: line_thickness_pixels

  • For Python, this parameter is expected to be an integer number >= 1, and the value would be treated as a line width in pixels (as it returns a raster image)

  • For JavaScript htis parameter is expected to be a ...

heatmap_mask

The visualization is the same as for a polygon_mask


Talk to sales

Last updated

Was this helpful?