def encodeMask(M):
    """
    Encode binary mask M using run-length encoding.
    :param   M (bool 2D array)  : binary mask to encode
    :return: R (object RLE)     : run-length encoding of binary mask
    """
    [h, w] = M.shape
    M = M.flatten(order='F')
    N = len(M)
    counts_list = []
    pos = 0
    # counts
    counts_list.append(1)
    diffs = np.logical_xor(M[0:N - 1], M[1:N])
    for diff in diffs:
        if diff:
            pos += 1
            counts_list.append(1)
        else:
            counts_list[pos] += 1
    # if array starts from 1. start with 0 counts for 0
    if M[0] == 1:
        counts_list = [0] + counts_list
    return {'size': [h, w],
            'counts': counts_list,
            }

    Encode binary mask M using run-length encoding.
    :param   M (bool 2D array)  : binary mask to encode
    :return: R (object RLE)     : run-length encoding of binary mask
    
lib/utils/mask_voc2coco.py