def outline(im):
    """ Input binary 2D (NxM) image. Ouput array (2xK) of K (y,x) coordinates
        where 0 <= K <= 2*M.
    """
topbottom = np.empty((1, 2 * im.shape[1]), dtype=np.uint16)
topbottom[(0), 0:im.shape[1]] = np.argmax(im, axis=0)
topbottom[(0), im.shape[1]:] = im.shape[0] - 1 - np.argmax(np.flipud(im),
    axis=0)
python contour for binary 2D matrix