def _fit_strel_to_im_3d(im, strel, r, x, y, z):
    r"""
    Helper function to add a structuring element to a 2D image.
    Used by RSA. Makes sure if center is less than r pixels from edge of image
    that the strel is sliced to fit.
    """
    elem = strel.copy()
    x_dim, y_dim, z_dim = im.shape
    x_min = x-r
    x_max = x+r+1
    y_min = y-r
    y_max = y+r+1
    z_min = z-r
    z_max = z+r+1
    if x_min < 0:
        x_adj = -x_min
        elem = elem[x_adj:, :, :]
        x_min = 0
    elif x_max > x_dim:
        x_adj = x_max - x_dim
        elem = elem[:-x_adj, :, :]
    if y_min < 0:
        y_adj = -y_min
        elem = elem[:, y_adj:, :]
        y_min = 0
    elif y_max > y_dim:
        y_adj = y_max - y_dim
        elem = elem[:, :-y_adj, :]
    if z_min < 0:
        z_adj = -z_min
        elem = elem[:, :, z_adj:]
        z_min = 0
    elif z_max > z_dim:
        z_adj = z_max - z_dim
        elem = elem[:, :, :-z_adj]
    ex, ey, ez = elem.shape
    im[x_min:x_min+ex, y_min:y_min+ey, z_min:z_min+ez] += elem
    return im