Пример #1
0
def correlate2d(im1,im2, boundary='wrap', **kwargs):
    """
    Cross-correlation of two images of arbitrary size.  Returns an image
    cropped to the largest of each dimension of the input images

    Options
    -------
    return_fft - if true, return fft(im1)*fft(im2[::-1,::-1]), which is the power
        spectral density
    fftshift - if true, return the shifted psd so that the DC component is in
        the center of the image
    pad - Default on.  Zero-pad image to the nearest 2^n
    crop - Default on.  Return an image of the size of the largest input image.
        If the images are asymmetric in opposite directions, will return the largest 
        image in both directions.
    boundary: str, optional
        A flag indicating how to handle boundaries:
            * 'fill' : set values outside the array boundary to fill_value
                       (default)
            * 'wrap' : periodic boundary

    WARNING: Normalization may be arbitrary if you use the PSD
    """

    return convolve(np.conjugate(im1), im2[::-1, ::-1], normalize_kernel=False,
            boundary=boundary, ignore_edge_zeros=False, **kwargs)
Пример #2
0
def smooth(image, kernelwidth=3, kerneltype='gaussian', trapslope=None,
        silent=True, psf_pad=True, interp_nan=False, nwidths='max',
        min_nwidths=6, return_kernel=False, normalize_kernel=np.sum,
        downsample=False, downsample_factor=None, ignore_edge_zeros=False,
        **kwargs):
    """
    Returns a smoothed image using a gaussian, boxcar, or tophat kernel

    Parameters
    ----------
    kernelwidth:
        width of kernel in pixels  (see definitions below)
    kerneltype:
        gaussian, boxcar, or tophat.  
        For a gaussian, uses a gaussian with sigma = kernelwidth (in pixels)
            out to [nwidths]-sigma
        A boxcar is a kernelwidth x kernelwidth square 
        A tophat is a flat circle with radius = kernelwidth

    psf_pad: [True]
        will pad the input image to be the image size + PSF.
        Slows things down but removes edge-wrapping effects (see convolve)
        This option should be set to false if the edges of your image are
        symmetric.
    interp_nan: [False]
        Will replace NaN points in an image with the
        smoothed average of its neighbors (you can still simply ignore NaN 
        values by setting ignore_nan=True but leaving interp_nan=False)
    silent: [True]
        turn it off to get verbose statements about kernel types
    return_kernel: [False]
        If set to true, will return the kernel as the
        second return value
    nwidths: ['max']
        number of kernel widths wide to make the kernel.  Set to 'max' to
        match the image shape, otherwise use any integer 
    min_nwidths: [6]
        minimum number of gaussian widths to make the kernel
        (the kernel will be larger than the image if the image size is <
        min_widths*kernelsize)
    normalize_kernel:
        Should the kernel preserve the map sum (i.e. kernel.sum() = 1)
        or the kernel peak (i.e. kernel.max() = 1) ?  Must be a *function* that can
        operate on a numpy array
    downsample:
        downsample after smoothing?
    downsample_factor:
        if None, default to kernelwidth
    ignore_edge_zeros: bool
        Ignore the zero-pad-created zeros.  This will effectively decrease
        the kernel area on the edges but will not re-normalize the kernel.
        This parameter may result in 'edge-brightening' effects if you're using
        a normalized kernel

    Note that the kernel is forced to be even sized on each axis to assure no
    offset when smoothing.
    """

    if (kernelwidth*min_nwidths > image.shape[0] or kernelwidth*min_nwidths > image.shape[1]):
        nwidths = min_nwidths
    if (nwidths!='max'):# and kernelwidth*nwidths < image.shape[0] and kernelwidth*nwidths < image.shape[1]):
        dimsize = np.ceil(kernelwidth*nwidths)
        dimsize += dimsize % 2
        yy,xx = np.indices([dimsize,dimsize])
        szY,szX = dimsize,dimsize
    else:
        szY,szX = image.shape
        szY += szY % 2
        szX += szX % 2
        yy,xx = np.indices([szY,szX])
    shape = (szY,szX)
    if not silent: print "Kernel size set to ",shape

    kernel = make_kernel(shape, kernelwidth=kernelwidth, kerneltype=kerneltype,
            normalize_kernel=normalize_kernel, trapslope=trapslope)

    if not silent: print "Kernel of type %s normalized with %s has peak %g" % (kerneltype, normalize_kernel, kernel.max())

    bad = (image != image)
    temp = image.copy() # to preserve NaN values
    # convolve does this already temp[bad] = 0

    # kwargs parsing to avoid duplicate keyword passing
    #if not kwargs.has_key('ignore_edge_zeros'): kwargs['ignore_edge_zeros']=True
    if not kwargs.has_key('interpolate_nan'): kwargs['interpolate_nan']=interp_nan

    # No need to normalize - normalization is dealt with in this code
    temp = convolve(temp,kernel,psf_pad=psf_pad, normalize_kernel=False,
            ignore_edge_zeros=ignore_edge_zeros, **kwargs)
    if interp_nan is False: temp[bad] = image[bad]

    if temp.shape != image.shape:
        raise ValueError("Output image changed size; this is completely impossible.")

    if downsample:
        if downsample_factor is None: downsample_factor = kernelwidth
        if return_kernel: return downsample_2d(temp,downsample_factor),downsample_2d(kernel,downsample_factor)
        else: return downsample_2d(temp,downsample_factor)
    else:
        if return_kernel: return temp,kernel
        else: return temp
Пример #3
0
def smooth(image, kernelwidth=3, kerneltype='gaussian', trapslope=None,
        silent=True, psf_pad=True, interpolate_nan=False, nwidths='max',
        min_nwidths=6, return_kernel=False, normalize_kernel=np.sum,
        downsample=False, downsample_factor=None, ignore_edge_zeros=False,
        use_fft=True,
        **kwargs):
    """
    Returns a smoothed image using a gaussian, boxcar, or tophat kernel

    Parameters
    ----------
    kernelwidth:
        width of kernel in pixels  (see definitions below)
    kerneltype:
        gaussian, boxcar, or tophat.  
        For a gaussian, uses a gaussian with sigma = kernelwidth (in pixels)
            out to [nwidths]-sigma
        A boxcar is a kernelwidth x kernelwidth square 
        A tophat is a flat circle with radius = kernelwidth

    psf_pad: [True]
        will pad the input image to be the image size + PSF.
        Slows things down but removes edge-wrapping effects (see convolve)
        This option should be set to false if the edges of your image are
        symmetric.
    interpolate_nan: [False]
        Will replace NaN points in an image with the
        smoothed average of its neighbors (you can still simply ignore NaN 
        values by setting ignore_nan=True but leaving interpolate_nan=False)
    silent: [True]
        turn it off to get verbose statements about kernel types
    return_kernel: [False]
        If set to true, will return the kernel as the
        second return value
    nwidths: ['max']
        number of kernel widths wide to make the kernel.  Set to 'max' to
        match the image shape, otherwise use any integer 
    min_nwidths: [6]
        minimum number of gaussian widths to make the kernel
        (the kernel will be larger than the image if the image size is <
        min_widths*kernelsize)
    normalize_kernel:
        Should the kernel preserve the map sum (i.e. kernel.sum() = 1)
        or the kernel peak (i.e. kernel.max() = 1) ?  Must be a *function* that can
        operate on a numpy array
    downsample:
        downsample after smoothing?
    downsample_factor:
        if None, default to kernelwidth
    ignore_edge_zeros: bool
        Ignore the zero-pad-created zeros.  This will effectively decrease
        the kernel area on the edges but will not re-normalize the kernel.
        This parameter may result in 'edge-brightening' effects if you're using
        a normalized kernel

    Note that the kernel is forced to be even sized on each axis to assure no
    offset when smoothing.
    """

    if (kernelwidth*min_nwidths > image.shape[0] or kernelwidth*min_nwidths > image.shape[1]):
        nwidths = min_nwidths
    if (nwidths!='max'):# and kernelwidth*nwidths < image.shape[0] and kernelwidth*nwidths < image.shape[1]):
        dimsize = np.ceil(kernelwidth*nwidths)
        dimsize += dimsize % 2
        yy,xx = np.indices([dimsize,dimsize])
        szY,szX = dimsize,dimsize
    else:
        szY,szX = image.shape
        szY += szY % 2
        szX += szX % 2
        yy,xx = np.indices([szY,szX])
    shape = (szY,szX)
    if not silent: print "Kernel size set to ",shape

    kernel = make_kernel(shape, kernelwidth=kernelwidth, kerneltype=kerneltype,
            normalize_kernel=normalize_kernel, trapslope=trapslope)

    if not silent: print "Kernel of type %s normalized with %s has peak %g" % (kerneltype, normalize_kernel, kernel.max())

    bad = (image != image)
    temp = image.copy() # to preserve NaN values
    # convolve does this already temp[bad] = 0

    # kwargs parsing to avoid duplicate keyword passing
    #if not kwargs.has_key('ignore_edge_zeros'): kwargs['ignore_edge_zeros']=True
    if not kwargs.has_key('interpolate_nan'): kwargs['interpolate_nan']=interpolate_nan

    if use_fft:
        # No need to normalize - normalization is dealt with in this code
        temp = convolve(temp,kernel,psf_pad=psf_pad, normalize_kernel=False,
                ignore_edge_zeros=ignore_edge_zeros, **kwargs)
    else:
        temp = convolve_cy(temp,kernel, **kwargs)
    if interpolate_nan is False: temp[bad] = image[bad]

    if temp.shape != image.shape:
        raise ValueError("Output image changed size; this is completely impossible.")

    if downsample:
        if downsample_factor is None: downsample_factor = kernelwidth
        if return_kernel: return downsample_2d(temp,downsample_factor),downsample_2d(kernel,downsample_factor)
        else: return downsample_2d(temp,downsample_factor)
    else:
        if return_kernel: return temp,kernel
        else: return temp