willemolding
8/17/2015 - 1:25 AM

Segmentation algorithm evaluation functions

Segmentation algorithm evaluation functions

from rasterio import features
from shapely.geometry import Polygon
from skimage.segmentation import find_boundaries
from skimage.morphology import binary_dilation, disk
import numpy as np


def undersegmentation_error(gt_segments, superpixels):
    """
    Computes the undersegmentation error metric. An efficient implementation. 

    Neubert, Peer and Protzel, Peter - 'Superpixel benchmark and comparison' - (2012)

    """
    # map the images to zero based sequential labelling
    S_labels, S_mapped = np.unique(gt_segments,  return_inverse=True)
    P_labels, P_mapped = np.unique(superpixels,  return_inverse=True)

    # calculate the 2d histogram
    H = np.histogram2d(S_mapped, P_mapped, bins=[len(S_labels),len(P_labels)])[0]

    return np.sum(np.fmin(H,np.sum(H,axis=0) - H)) / gt_segments.size


def boundary_recall(gt_segments, superpixels, r=1):
    """
    Calculates the boundary recall and bounday precision

    r is the radius in pixels from the ground truth boundary that the superpixel boundary can be
    """
    # Extract only the boundaries from the ground truth
    gt_boundary_img = find_boundaries(gt_segments)
    gt_boundary_img = binary_dilation(gt_boundary_img, selem=disk(r))
    superpixel_boundary_img = find_boundaries(superpixels)

    tp = np.sum(np.logical_and(gt_boundary_img, superpixel_boundary_img))
    fn = np.sum(np.logical_and(gt_boundary_img, ~superpixel_boundary_img))

    recall = float(tp)/(tp+fn)

    return recall