コード例 #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')
コード例 #2
0
ファイル: test_utils.py プロジェクト: bsipocz/gammapy
def test_process_image_pixels():
    """Check the example how to implement convolution given in the docstring"""
    from astropy.convolution import convolve as astropy_convolve

    def convolve(image, kernel):
        """Convolve image with kernel"""
        from ..utils import process_image_pixels
        images = dict(image=np.asanyarray(image))
        kernel = np.asanyarray(kernel)
        out = dict(image=np.empty_like(image))

        def convolve_function(images, kernel):
            value = np.sum(images['image'] * kernel)
            return dict(image=value)

        process_image_pixels(images, kernel, out, convolve_function)
        return out['image']

    random_state = np.testing.RandomState(seed=0)

    image = random_state.uniform(size=(7, 10))
    kernel = random_state.uniform(size=(3, 5))
    actual = convolve(image, kernel)
    desired = astropy_convolve(image, kernel, boundary='fill')
    assert_allclose(actual, desired)
コード例 #3
0
def convolve(sunpy_map, oversample_psf=1):
    """Convolve the FOXSI psf with an input map

    Parameters
    ----------
    sunpy_map : `~sunpy.map.GenericMap`
        An input map.
    oversample_psf : int
        The number of subpixels to average over to produce a more accurate PSF

    Returns
    -------
    sunpy_map : `~sunpy.map.GenericMap`
        The map convolved with the FOXSI psf.
    """

    this_psf = psf(0 * u.arcmin,
                   0 * u.arcmin,
                   scale=sunpy_map.scale.x,
                   oversample=oversample_psf)

    smoothed_data = astropy_convolve(sunpy_map.data, this_psf)
    meta = sunpy_map.meta.copy()
    meta['telescop'] = 'FOXSI-SMEX'
    result = Map((smoothed_data, meta))

    return result
コード例 #4
0
ファイル: test_utils.py プロジェクト: vorugantia/gammapy
def test_process_image_pixels():
    """Check the example how to implement convolution given in the docstring"""
    from astropy.convolution import convolve as astropy_convolve

    def convolve(image, kernel):
        """Convolve image with kernel"""
        from ..utils import process_image_pixels
        images = dict(image=np.asanyarray(image))
        kernel = np.asanyarray(kernel)
        out = dict(image=np.empty_like(image))

        def convolve_function(images, kernel):
            value = np.sum(images['image'] * kernel)
            return dict(image=value)

        process_image_pixels(images, kernel, out, convolve_function)
        return out['image']

    random_state = np.testing.RandomState(seed=0)

    image = random_state.uniform(size=(7, 10))
    kernel = random_state.uniform(size=(3, 5))
    actual = convolve(image, kernel)
    desired = astropy_convolve(image, kernel, boundary='fill')
    assert_allclose(actual, desired)
コード例 #5
0
ファイル: convolve_util.py プロジェクト: AlexaVillaume/aplpy
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')
コード例 #6
0
ファイル: utils.py プロジェクト: aflp91/fink-science-portal
def convolve(image, smooth=3, kernel='gauss'):
    """ Convolve 2D image. Hacked from aplpy
    """
    if smooth is None and isinstance(kernel, str) 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 isinstance(kernel, str):
        if kernel == 'gauss':
            kernel = Gaussian2DKernel(
                smooth, x_size=smooth * 5, y_size=smooth * 5)
        elif kernel == 'box':
            kernel = Box2DKernel(smooth, x_size=smooth * 5, y_size=smooth * 5)
        else:
            raise ValueError("Unknown kernel: {0}".format(kernel))

    return astropy_convolve(image, kernel, boundary='extend')
コード例 #7
0
def test_convolve_identical_to_astropy():
    array = np.random.normal(5, 0.5, 1000).reshape(10, 10, 10)
    kernel = np.ones((3, 3, 3))
    conv1 = convolve_with_mask(array, kernel)
    conv2 = astropy_convolve(array, kernel)
    # Because of different boundary handling the first and last element in each
    # dimension must be ignored.
    assert_array_almost_equal(conv1[1:-1, 1:-1, 1:-1], conv2[1:-1, 1:-1, 1:-1])
コード例 #8
0
ファイル: psf.py プロジェクト: wafels/foxsi-smex
def convolve(sunpy_map, oversample_psf=1):
    """Convolve the FOXSI psf with an input map

    Parameters
    ----------
    sunpy_map : `~sunpy.map.GenericMap`
        An input map.
    oversample_psf : int
        The number of subpixels to average over to produce a more accurate PSF

    Returns
    -------
    sunpy_map : `~sunpy.map.GenericMap`
        The map convolved with the FOXSI psf.
    """

    this_psf = psf(0 * u.arcmin, 0 * u.arcmin, scale=sunpy_map.scale.x, oversample=oversample_psf)

    smoothed_data = astropy_convolve(sunpy_map.data, this_psf)
    meta = sunpy_map.meta.copy()
    meta["telescop"] = "FOXSI-SMEX"
    result = Map((smoothed_data, meta))

    return result
コード例 #9
0
N = 256  # map size
pix = 10.0 * ARCSEC_TO_RADIAN
FITS = MakeEmptyFitsDim(1.0, 0.0, pix, N, N)
FITS[0].data = asarray(3.0 + randn(N, N), float32)
FITS[0].data = clip(FITS[0].data, 1.0, 10.0)

fwhm_pix = 7.3
fwhm_rad = fwhm_pix * pix
sigma_pix = fwhm_pix / sqrt(8.0 * log(2.0))
kernel = Gaussian2DKernel(x_stddev=sigma_pix)
if (kernel.shape[0] % 2 == 0):
    print("kernel dimensions must be odd")
    sys.exit()

AP = astropy_convolve(FITS[0].data.copy(), kernel, boundary='extend')
if (0):
    CL = ConvolveFitsBeamPyCL(FITS, kernel, border='ignore')[0].data.copy()
else:
    CL = ConvolveFitsBeamPyCL(FITS, kernel, border='nearest')[0].data.copy()

figure(1, figsize=(8, 6))
rc('font', size=9)
subplots_adjust(left=0.09,
                right=0.94,
                bottom=0.09,
                top=0.95,
                wspace=0.26,
                hspace=0.3)

subplot(221)
コード例 #10
0
     do_it = 1
     if (i>0):
         if (TIME[i-1,iprog]>10.0):
             do_it = 0  # it was already taking too long
             TIME[i, iprog] = 1e10
     if (0): # we have problem on the Intel GPU -- i915 bug prevents long runs ??
         if ((iprog==4)&(fwhm_pix>32)): do_it = False
     if (do_it):
         time.sleep(SLEEP)
         t0 = time.time()
         if (iprog==0):
             A = convolve_map_fast(FITS[0].data.copy(), fwhm_pix, radius=1.7*fwhm_pix)
         elif (iprog==1):
             B = scipy_convolve(FITS[0].data.copy(), kernel, mode='same', method='direct')                
         elif (iprog==2):
             C = astropy_convolve(FITS[0].data.copy(), kernel)
         elif (iprog==3):
             # ConvolveFitsPyCL(F, fwhm_rad, fwhm_orig=0.0, RinFWHM=1.7, GPU=0, platforms=[2,])
             D = ConvolveFitsBeamPyCL(FITS, kernel, GPU=0)[0].data.copy()
         elif (iprog==4):  # on my system Intel GPU
             # ConvolveFitsPyCL(F, fwhm_rad, fwhm_orig=0.0, RinFWHM=1.7, GPU=1, platforms=[0,])
             E = ConvolveFitsBeamPyCL(FITS, kernel, GPU=1)[0].data.copy()
         elif (iprog==5):  # on my system NVidia GPU
             # ConvolveFitsPyCL(F, fwhm_rad, fwhm_orig=0.0, RinFWHM=1.7, GPU=1, platforms=[1,])
             F = ConvolveFitsBeamPyCL(FITS, kernel, GPU=1, platforms=[1,])[0].data.copy()
         TIME[i, iprog] = time.time()-t0
 if (i==-1):
     clf()
     subplot(221)
     imshow(C)
     colorbar()