Exemplo n.º 1
0
def test_estimate_cdelt():
    l, b = 0, 0

    # This is the ra,dec of l,b=0,0
    ra, dec = 266.404497776, -28.9364329295

    # This is 'almost' the ra,dec of l,b=0,0 - works
    # ra,dec=266.40,-28.93

    wcs = pywcs.WCS(naxis=2)

    wcs.wcs.crpix = [5.5, 5.5]
    wcs.wcs.cdelt = [0.1, -0.1]
    wcs.wcs.crval = [l, b]
    wcs.wcs.ctype = ["GLON-ZEA".encode("ascii"), "GLAT-ZEA".encode("ascii")]

    import stregion.wcs_helper as wcs_helper
    proj = wcs_helper.get_kapteyn_projection(wcs)
    cdelt = wcs_helper.estimate_cdelt(proj, 5.5, 5.5)

    assert np.allclose([cdelt], [0.1])

    region_string = "fk5; circle(%s, %s, 0.5000)" % (ra, dec)
    reg = stregion.parse(region_string).as_imagecoord(wcs)

    assert np.allclose([reg[0].coord_list[-1]], [0.5 / 0.1])
Exemplo n.º 2
0
    def _combine_exclude_mask(self, mask):
        # create masks from exclude/include regions and combine it with the
        # input DQ mask:
        #
        regmask = None
        if self.src_find_filters is not None and \
           'region_file' in self.src_find_filters:
            reg_file_name = self.src_find_filters['region_file']
            if not os.path.isfile(reg_file_name):
                raise IOError(
                    "The 'exclude' region file '{:s}' does not exist.".format(
                        reg_file_name))
        else:
            return mask

        # get data image size:
        (img_ny, img_nx) = self.source.shape

        # find out if user provided a region file or a mask FITS file:
        reg_file_ext = os.path.splitext(reg_file_name)[-1]
        if reg_file_ext.lower().strip() in ['.fits', '.fit'] and \
           basicFITScheck(reg_file_name):
            # likely we are dealing with a FITS file.
            # check that the file is a simple with 2 axes:
            hdulist = fits.open(reg_file_name, memmap=False)
            extlist = get_extver_list(hdulist, extname=None)
            for ext in extlist:
                usermask = hdulist[ext].data
                if usermask.shape == (img_ny, img_nx):
                    regmask = usermask.astype(np.bool)
                    break
            hdulist.close()
            if regmask is None:
                raise ValueError("None of the image-like extensions in the "
                                 "user-provided exclusion mask '{}' has a "
                                 "correct shape".format(reg_file_name))

        else:
            # we are dealing with a region file:
            reglist = pyregion.open(reg_file_name)

            ## check that regions are in image-like coordinates:
            ##TODO: remove the code below once 'pyregion' package can correctly
            ##      (DS9-like) convert sky coordinates to image coordinates for all
            ##      supported shapes.
            #if not all([ (x.coord_format == 'image' or \
            #              x.coord_format == 'physical') for x in reglist]):
            #    print("WARNING: Some exclusion regions are in sky coordinates.\n"
            #          "         These regions will be ignored.")
            #    # filter out regions in sky coordinates:
            #    reglist = pyregion.ShapeList(
            #        [x for x in reglist if x.coord_format == 'image' or \
            #         x.coord_format == 'physical']
            #    )

            #TODO: comment out next lines if we do not support region files
            #      in sky coordinates and uncomment previous block:
            # Convert regions from sky coordinates to image coordinates:
            auxwcs = _AuxSTWCS(self.wcs)
            reglist = reglist.as_imagecoord(auxwcs, rot_wrt_axis=2)

            # if all regions are exclude regions, then assume that the entire image
            # should be included and that exclude regions exclude from this
            # rectangular region representing the entire image:
            if all([x.exclude for x in reglist]):
                # we slightly widen the box to make sure that
                # the entire image is covered:
                imreg = pyregion.parse(
                    "image;box({:.1f},{:.1f},{:d},{:d},0)".format(
                        (img_nx + 1) / 2.0, (img_ny + 1) / 2.0, img_nx + 1,
                        img_ny + 1))

                reglist = pyregion.ShapeList(imreg + reglist)

            # create a mask from regions:
            regmask = np.asarray(reglist.get_mask(shape=(img_ny, img_nx)),
                                 dtype=np.bool)

        if mask is not None and regmask is not None:
            mask = np.logical_and(regmask, mask)
        else:
            mask = regmask

        #DEBUG:
        if mask is not None:
            fn = os.path.splitext(self.fname)[0] + '_srcfind_mask.fits'
            fits.writeto(fn, mask.astype(dtype=np.uint8), overwrite=True)

        return mask
Exemplo n.º 3
0
    def _combine_exclude_mask(self, mask):
        # create masks from exclude/include regions and combine it with the
        # input DQ mask:
        #
        regmask = None
        if self.src_find_filters is not None and \
           'region_file' in self.src_find_filters:
            reg_file_name = self.src_find_filters['region_file']
            if not os.path.isfile(reg_file_name):
                raise IOError("The 'exclude' region file '{:s}' does not exist."
                              .format(reg_file_name))
        else:
            return mask

        # get data image size:
        (img_ny, img_nx) = self.source.shape

        # find out if user provided a region file or a mask FITS file:
        reg_file_ext = os.path.splitext(reg_file_name)[-1]
        if reg_file_ext.lower().strip() in ['.fits', '.fit'] and \
           basicFITScheck(reg_file_name):
            # likely we are dealing with a FITS file.
            # check that the file is a simple with 2 axes:
            hdulist = fits.open(reg_file_name, memmap=False)
            extlist = get_extver_list(hdulist,extname=None)
            for ext in extlist:
                usermask = hdulist[ext].data
                if usermask.shape == (img_ny, img_nx):
                    regmask = usermask.astype(np.bool)
                    break
            hdulist.close()
            if regmask is None:
                raise ValueError("None of the image-like extensions in the "
                                 "user-provided exclusion mask '{}' has a "
                                 "correct shape".format(reg_file_name))

        else:
            # we are dealing with a region file:
            reglist = pyregion.open(reg_file_name)

            ## check that regions are in image-like coordinates:
            ##TODO: remove the code below once 'pyregion' package can correctly
            ##      (DS9-like) convert sky coordinates to image coordinates for all
            ##      supported shapes.
            #if not all([ (x.coord_format == 'image' or \
            #              x.coord_format == 'physical') for x in reglist]):
            #    print("WARNING: Some exclusion regions are in sky coordinates.\n"
            #          "         These regions will be ignored.")
            #    # filter out regions in sky coordinates:
            #    reglist = pyregion.ShapeList(
            #        [x for x in reglist if x.coord_format == 'image' or \
            #         x.coord_format == 'physical']
            #    )

            #TODO: comment out next lines if we do not support region files
            #      in sky coordinates and uncomment previous block:
            # Convert regions from sky coordinates to image coordinates:
            auxwcs    = _AuxSTWCS(self.wcs)
            reglist = reglist.as_imagecoord(auxwcs, rot_wrt_axis=2)

            # if all regions are exclude regions, then assume that the entire image
            # should be included and that exclude regions exclude from this
            # rectangular region representing the entire image:
            if all([x.exclude for x in reglist]):
                # we slightly widen the box to make sure that
                # the entire image is covered:
                imreg = pyregion.parse("image;box({:.1f},{:.1f},{:d},{:d},0)"
                                       .format((img_nx+1)/2.0, (img_ny+1)/2.0,
                                               img_nx+1, img_ny+1)
                                       )

                reglist = pyregion.ShapeList(imreg + reglist)

            # create a mask from regions:
            regmask = np.asarray(
                reglist.get_mask(shape=(img_ny, img_nx)),
                dtype=np.bool
            )

        if mask is not None and regmask is not None:
            mask = np.logical_and(regmask, mask)
        else:
            mask = regmask

        #DEBUG:
        if mask is not None:
            fn = os.path.splitext(self.fname)[0] + '_srcfind_mask.fits'
            fits.writeto(fn, mask.astype(dtype=np.uint8), overwrite=True)

        return mask
Exemplo n.º 4
0
    return rp.filter_shape(sss3)


def get_mask(region, hdu, origin=1):
    """
    f = pyfits.read("test.fits")
    reg = read_region_as_imagecoord(s, f[0].header)
    mask = get_mask(reg, f[0])
    """

    from stregion.region_to_filter import as_region_filter

    data = hdu.data
    #header = hdu.header

    region_filter = as_region_filter(region, origin=origin)

    mask = region_filter.mask(data)

    return mask


if __name__ == '__main__':
    #reg = stregion.open("../mos_fov.reg")
    import stregion
    proposed_fov = 'fk5;circle(290.96388,14.019167,843.31194")'
    reg = stregion.parse(proposed_fov)
    reg_imagecoord = reg.as_imagecoord(header)
    patches, txts = reg.get_mpl_patches_texts()
    m = reg.get_mask(hdu=f[0])
Exemplo n.º 5
0
import matplotlib.pyplot as plt
import stregion

region = """
image
circle(100, 100, 80)
box(200, 150, 150, 120, 0)
"""

r = stregion.parse(region)
mask_1or2 = r.get_mask(shape=(300,300))

myfilter = r.get_filter()
mask_1and2 = (myfilter[0] & myfilter[1]).mask((300,300))

plt.subplot(121).imshow(mask_1or2, origin="lower", interpolation="nearest")
plt.subplot(122).imshow(mask_1and2, origin="lower", interpolation="nearest")
plt.show()