Pad positively with 0 or negatively (cut)

    Parameters
    ----------
    im: 2d array
        The image
    pad: 4 numbers
        (ytop, ybottom, xleft, xright) or (imin, imax, jmin, jmax)

    Returns
    -------
    im: 2d array
        The padded (or cropped) image
    offset: 2 numbers
        The offset related to the input image

    Notes
    -----
    This changes the size of the image

def pad_img(im, pad):
    """Pad positively with 0 or negatively (cut)

    Parameters
    ----------
    im: 2d array
        The image
    pad: 4 numbers
        (ytop, ybottom, xleft, xright) or (imin, imax, jmin, jmax)

    Returns
    -------
    im: 2d array
        The padded (or cropped) image
    offset: 2 numbers
        The offset related to the input image

    Notes
    -----
    This changes the size of the image
    """
    im = np.asarray(im)
    pad = np.asarray(pad)
    # get shape
    shape = im.shape
    # extract offset from padding
    offset = -pad[::2]
    # if the padding is negatif, cut the matrix
    cut = pad < 0
    if cut.any():
        # Extract value for pad
        cut *= pad
        # the left/top components should be positive
        cut[::2] *= -1
        # The right/bottom components can't be 0, replace by shape0
        cut[1::2] += (cut[1::2] == 0) * shape
        # cut the image
        im = im[cut[0]:cut[1], cut[2]:cut[3]]
    # extract positive padding
    ppad = pad > 0
    if ppad.any():
        pad = pad * ppad
        # separate pad for application on matrix
        ypad = (pad[0], pad[1])
        xpad = (pad[2], pad[3])
        # prepare matrix
        im = np.lib.pad(im, (ypad, xpad), mode='mean')
    return im, offset