Convolve one image with another

    ANTsR function: `convolveImage`

    Arguments
    ---------
    image : ANTsImage
        image to convolve

    kernel_image : ANTsImage
        image acting as kernel

    crop : boolean
        whether to automatically crop kernel_image

    Returns
    -------
    ANTsImage

    Example
    -------
    >>> import ants
    >>> fi = ants.image_read(ants.get_ants_data('r16'))
    >>> convimg = ants.make_image( (3,3), (1,0,1,0,-4,0,1,0,1) )
    >>> convout = ants.convolve_image( fi, convimg )
    >>> convimg2 = ants.make_image( (3,3), (0,1,0,1,0,-1,0,-1,0) )
    >>> convout2 = ants.convolve_image( fi, convimg2 )

def convolve_image(image, kernel_image, crop=True):
    """
    Convolve one image with another

    ANTsR function: `convolveImage`

    Arguments
    ---------
    image : ANTsImage
        image to convolve

    kernel_image : ANTsImage
        image acting as kernel

    crop : boolean
        whether to automatically crop kernel_image

    Returns
    -------
    ANTsImage

    Example
    -------
    >>> import ants
    >>> fi = ants.image_read(ants.get_ants_data('r16'))
    >>> convimg = ants.make_image( (3,3), (1,0,1,0,-4,0,1,0,1) )
    >>> convout = ants.convolve_image( fi, convimg )
    >>> convimg2 = ants.make_image( (3,3), (0,1,0,1,0,-1,0,-1,0) )
    >>> convout2 = ants.convolve_image( fi, convimg2 )
    """
    if not isinstance(image, iio.ANTsImage):
        raise ValueError('image must be ANTsImage type')
    if not isinstance(kernel_image, iio.ANTsImage):
        raise ValueError('kernel must be ANTsImage type')
    
    orig_ptype = image.pixeltype
    if image.pixeltype != 'float':
        image = image.clone('float')
    if kernel_image.pixeltype != 'float':
        kernel_image = kernel_image.clone('float')

    if crop:
        kernel_image_mask = utils.get_mask(kernel_image)
        kernel_image = utils.crop_image(kernel_image, kernel_image_mask)
        kernel_image_mask = utils.crop_image(kernel_image_mask, kernel_image_mask)
        kernel_image[kernel_image_mask==0] = kernel_image[kernel_image_mask==1].mean()

    libfn = utils.get_lib_fn('convolveImageF%i' % image.dimension)
    conv_itk_image = libfn(image.pointer, kernel_image.pointer)
    conv_ants_image = iio.ANTsImage(pixeltype=image.pixeltype, dimension=image.dimension,
                                    components=image.components, pointer=conv_itk_image)

    if orig_ptype != 'float':
        conv_ants_image = conv_ants_image.clone(orig_ptype)

    return conv_ants_image