<gh_stars>0
import numpy as np
import cv2
import torch

def mask2rle(img):
    '''
    Convert mask to rle.
    img: numpy array, 1 - mask, 0 - background
    Returns run length as string formated
    '''
    pixels = img.T.flatten()
    pixels = np.concatenate([[0], pixels, [0]])
    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
    runs[1::2] -= runs[::2]
    return ' '.join(str(x) for x in runs)

def post_process(probability, threshold, min_size):
    """
    Post processing of each predicted mask, components with lesser number of pixels
    than `min_size` are ignored
    """
    # don't remember where I saw it
    mask = cv2.threshold(probability, threshold, 1, cv2.THRESH_BINARY)[1]
    num_component, component = cv2.connectedComponents(mask.astype(np.uint8))
    predictions = np.zeros((256, 1600), np.float32)
    num = 0
    for c in range(1, num_component):
        p = (component == c)
        if p.sum() > min_size:
            predictions[p] = 1
            num += 1
    return predictions, num

def sigmoid(x):
    """
    Sigmoid activation function; transforms input, x, into mutually exclusive probabilities.
    Args:
        x: np.ndarray, list, or tuple
    Returns:
        np.ndarray with the same shape as x, with probabilities from 0-1
    """
    return 1 / (1 + np.exp(-x))

def load_weights_infer(checkpoint_path, model):
    """
    Loads pytorch model from a checkpoint and into inference mode.

    Args:
        checkpoint_path (str): path to a .pt or .pth checkpoint
        model (torch.nn.Module): <-
    Returns:
        Model with loaded weights and in evaluation mode
    """
    state_dict = torch.load(checkpoint_path, map_location="cpu")["model_state_dict"]
    model.load_state_dict(state_dict, strict=True)
    model.eval()
    return model

import numpy as np
import cv2
import torch

def mask2rle(img):
    '''
    Convert mask to rle.
    img: numpy array, 1 - mask, 0 - background
    Returns run length as string formated
    '''
    pixels = img.T.flatten()
    pixels = np.concatenate([[0], pixels, [0]])
    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
    runs[1::2] -= runs[::2]
    return ' '.join(str(x) for x in runs)

def post_process(probability, threshold, min_size):
    """
    Post processing of each predicted mask, components with lesser number of pixels
    than `min_size` are ignored
    """
    # don't remember where I saw it
    mask = cv2.threshold(probability, threshold, 1, cv2.THRESH_BINARY)[1]
    num_component, component = cv2.connectedComponents(mask.astype(np.uint8))
    predictions = np.zeros((256, 1600), np.float32)
    num = 0
    for c in range(1, num_component):
        p = (component == c)
        if p.sum() > min_size:
            predictions[p] = 1
            num += 1
    return predictions, num

def sigmoid(x):
    """
    Sigmoid activation function; transforms input, x, into mutually exclusive probabilities.
    Args:
        x: np.ndarray, list, or tuple
    Returns:
        np.ndarray with the same shape as x, with probabilities from 0-1
    """
    return 1 / (1 + np.exp(-x))

def load_weights_infer(checkpoint_path, model):
    """
    Loads pytorch model from a checkpoint and into inference mode.

    Args:
        checkpoint_path (str): path to a .pt or .pth checkpoint
        model (torch.nn.Module): <-
    Returns:
        Model with loaded weights and in evaluation mode
    """
    state_dict = torch.load(checkpoint_path, map_location="cpu")["model_state_dict"]
    model.load_state_dict(state_dict, strict=True)
    model.eval()
    return model
Convert mask to rle.     img: numpy array, 1 - mask, 0 - background     Returns run length as string formated Post processing of each predicted mask, components with lesser number of pixels     than `min_size` are ignored # don't remember where I saw it Sigmoid activation function; transforms input, x, into mutually exclusive probabilities.     Args:         x: np.ndarray, list, or tuple     Returns:         np.ndarray with the same shape as x, with probabilities from 0-1 Loads pytorch model from a checkpoint and into inference mode.      Args:         checkpoint_path (str): path to a .pt or .pth checkpoint         model (torch.nn.Module): <-     Returns:         Model with loaded weights and in evaluation mode