Beispiel #1
0
def convolve(image, smooth=3, kernel='gauss'):

    if smooth is None and kernel in ['box', 'gauss']:
        return image

    if smooth is not None and not np.isscalar(smooth):
        raise ValueError("smooth= should be an integer - for more complex "
                         "kernels, pass an array containing the kernel "
                         "to the kernel= option")

    # The Astropy convolution doesn't treat +/-Inf values correctly yet, so we
    # convert to NaN here.

    image_fixed = np.array(image, dtype=float, copy=True)
    image_fixed[np.isinf(image)] = np.nan

    if kernel == 'gauss':
        if make_kernel is None:
            kernel = Gaussian2DKernel(smooth,
                                      x_size=smooth * 5,
                                      y_size=smooth * 5)
        else:
            kernel = make_kernel((smooth * 5, smooth * 5), smooth, 'gaussian')
    elif kernel == 'box':
        if make_kernel is None:
            kernel = Box2DKernel(smooth, x_size=smooth * 5, y_size=smooth * 5)
        else:
            kernel = make_kernel((smooth * 5, smooth * 5), smooth, 'boxcar')
    else:
        kernel = kernel

    return astropy_convolve(image, kernel, boundary='extend')
Beispiel #2
0
def convolve(image, smooth=3, kernel='gauss'):

    if smooth is None and kernel in ['box', 'gauss']:
        return image

    if smooth is not None and not np.isscalar(smooth):
        raise ValueError("smooth= should be an integer - for more complex "
                         "kernels, pass an array containing the kernel "
                         "to the kernel= option")

    # The Astropy convolution doesn't treat +/-Inf values correctly yet, so we
    # convert to NaN here.

    image_fixed = np.array(image, dtype=float, copy=True)
    image_fixed[np.isinf(image)] = np.nan

    if kernel == 'gauss':
        if make_kernel is None:
            kernel = Gaussian2DKernel(smooth, x_size=smooth * 5, y_size=smooth * 5)
        else:
            kernel = make_kernel((smooth * 5, smooth * 5), smooth, 'gaussian')
    elif kernel == 'box':
        if make_kernel is None:
            kernel = Box2DKernel(smooth, x_size=smooth * 5, y_size=smooth * 5)
        else:
            kernel = make_kernel((smooth * 5, smooth * 5), smooth, 'boxcar')
    else:
        kernel = kernel

    return astropy_convolve(image, kernel, boundary='extend')
Beispiel #3
0
def convolve_images(images_with_headers):
    """
    Convolves all of the images to a common resolution using a simple
    gaussian kernel.

    Parameters
    ----------
    images_with_headers: zipped list structure
        A structure containing headers and image data for all FITS input
        images.

    """

    print("Convolving images")
    fwhm_input = get_fwhm_value(images_with_headers)
    print("fwhm_input = " + `fwhm_input`)

    for i in range(0, len(images_with_headers)):

        native_pixelscale = get_native_pixelscale(images_with_headers[i][1], get_instrument(images_with_headers[i][1]))
        sigma_input = fwhm_input / (2* math.sqrt(2*math.log (2) ) * native_pixelscale)
        print("Native pixel scale: " + `native_pixelscale`)
        print("Instrument: " + `get_instrument(images_with_headers[i][1])`)

        original_filename = os.path.basename(images_with_headers[i][2])
        original_directory = os.path.dirname(images_with_headers[i][2])
        new_directory = original_directory + "/convolved/"
        convolved_filename = new_directory + original_filename  + "_convolved.fits"
        input_directory = original_directory + "/registered/"
        input_filename = input_directory + original_filename  + "_registered.fits"
        print("Convolved filename: " + convolved_filename)
        print("Input filename: " + input_filename)
        if not os.path.exists(new_directory):
            os.makedirs(new_directory)

        # NOTETOSELF: there has been a loss of data from the data cubes at an earlier
        # step. The presence of 'EXTEND' and 'DSETS___' keywords in the header no
        # longer means that there is any data in hdulist[1].data. I am using a
        # workaround for now, but this needs to be looked at.
        hdulist = fits.open(input_filename)
        header = hdulist[0].header
        image_data = hdulist[0].data
        #if ('EXTEND' in header and 'DSETS___' in header):
            #image_data = hdulist[1].data
        #else:
            #image_data = hdulist[0].data
        hdulist.close()

        gaus_kernel_inp = make_kernel([3,3], kernelwidth=sigma_input, kerneltype='gaussian', trapslope=None, force_odd=True)

        # Do the convolution and save it as a new .fits file
        conv_result = convolve(image_data, gaus_kernel_inp)
        header['FWHM'] = (fwhm_input, 'The FWHM value used in the convolution step.')

        hdu = fits.PrimaryHDU(conv_result, header)
        print("Creating " + convolved_filename)
        hdu.writeto(convolved_filename, clobber=True)
def test_center():
    # Test dataset parameters
    kernel_shape = (11, 11)
    total_excess = 100
    total_background = 1000

    kernel = make_kernel(kernel_shape, kernelwidth=3, kerneltype='gaussian')
    excess = total_excess * make_kernel(kernel_shape, kernelwidth=kernel_shape[0], kerneltype='boxcar')
    background = total_background * make_kernel(kernel_shape, kernelwidth=kernel_shape[0], kerneltype='boxcar')
    counts = excess + background
    images = dict(counts=counts, background=background)
    
    probability = matched_filter.probability_center(images, kernel)
    # TODO: try to get a verified result
    assert_almost_equal(probability, 0.0043809799783148338)

    significance = matched_filter.significance_center(images, kernel)
    # TODO: try to get a verified result
    assert_almost_equal(significance, 2.6212048333735858)
def test_image():
    # Test dataset parameters
    kernel_shape = (11, 11)
    image_shape = (31, 31)
    total_excess = 100
    total_background = 1000
    
    # Create test dataset
    kernel = make_kernel(kernel_shape, kernelwidth=3, kerneltype='gaussian')
    excess = total_excess * make_kernel(image_shape, kernelwidth=3, kerneltype='gaussian')
    background = total_background * make_kernel(image_shape, kernelwidth=image_shape[0], kerneltype='boxcar')
    counts = excess + background
    #np.random.seed(0)
    #counts = np.random.poisson(counts)
    images = dict(counts=counts, background=background)

    probability = matched_filter.probability_image(images, kernel)
    # TODO: try to get a verified result
    assert_almost_equal(probability.max(), 0.4840923814509871)

    significance = matched_filter.significance_image(images, kernel)
    # TODO: try to get a verified result
    assert_almost_equal(significance.max(), 7.249351301729793)
Beispiel #6
0
if args.verbose: print ':: '+sys.argv[0]+' :: Sigma of gaussian kernel set to '+str(sigma)+' arcsec '

if args.pixsize:
    pixdim = args.pixsize
else:
    pixdim = 0.08 # arcsec - default BoRG drizzle pixel size

kernelwidth = sigma/pixdim
if args.verbose: print ':: '+sys.argv[0]+' :: Corresponding to a kernel width of '+str(kernelwidth)+' pixels with '+str(pixdim)+' arcsec/pixel'

dim        = np.ceil(kernelwidth*5)
if dim%2 == 0: dim = dim+1  # if dim is divisable by 2 (even) add 1 to get odd dimension
kerneldim  = [dim,dim]
if args.verbose: print ':: '+sys.argv[0]+' :: Kernel dimensions will be '+str(kerneldim)
kerneltype = 'gaussian' # possibilities: 'gaussian', 'boxcar', 'tophat', 'brickwall', 'airy', 'trapezoid'
kernel     = astro.make_kernel(kerneldim, kernelwidth,kerneltype) # creating kernel
#-------------------------------------------------------------------------------------------------------------
# looping over images and convolving
for ii in range(Nfiles):
    fitsIN   = files[ii]
    PNfitsIN = pathAname(fitsIN)
    hdulist  = pyfits.open(fitsIN)  # reading HDU list of fits image
    arrIN    = hdulist[0].data   # loading image into array
    imgdim   = arrIN.shape

    if dim > min(imgdim): # checking that kernel dimension is smaller than fits image dimension
        print ':: '+sys.argv[0]+' :: ERROR Dimesion of the kernel is larger than the input image:'
        print fitsIN
        print ':: '+sys.argv[0]+' :: --> ABORTING'
        sys.exit()