Пример #1
0
def align_for_diff(refpath, newpath, newmask=None):
    """Function to align two images using their paths,
    and returning newpaths for differencing.
    We will allways rotate and align the new image to the reference,
    so it is easier to compare differences along time series.
    """
    ref = np.ma.masked_invalid(fits.getdata(refpath))
    new = fits.getdata(newpath)
    hdr = fits.getheader(newpath)
    if newmask is not None:
        new = np.ma.masked_array(new, mask=fits.getdata(newmask))
    else:
        new = np.ma.masked_invalid(new)

    dest_file = 'aligned_'+os.path.basename(newpath)
    dest_file = os.path.join(os.path.dirname(newpath), dest_file)

    try:
        new2 = aa.register(new.filled(np.median(new)), ref)
    except ValueError:
        ref = ref.astype(float)
        new = new.astype(float)
        new2 = aa.register(new, ref)

    hdr.set('comment', 'aligned img '+newpath+' to '+refpath)
    if isinstance(new2, np.ma.masked_array):
        hdu = fits.HDUList([fits.PrimaryHDU(new2.data, header=hdr),
                            fits.ImageHDU(new2.mask.astype('uint8'))])
        hdu.writeto(dest_file, overwrite=True)
    else:
        fits.writeto(dest_file, new2, hdr, overwrite=True)

    return dest_file
def aligning(reduced_images, aligned_path, aligned_images, args):

    sloan_filters = set(reduced_images.summary['filter'])
    print('FILTERS USED:', sloan_filters)

    for fltr in sorted(sloan_filters):
        sloan_fltr = reduced_images.ccds(imagetyp='Light Frame',
                                         filter=fltr,
                                         return_fname=True,
                                         ccd_kwargs={'unit': 'adu'})
        sloan_fltr_list = list(sloan_fltr)
        ref_im = sloan_fltr_list[0][0]

        for light, file_name in sloan_fltr_list:

            aligned_light = light.copy()
            try:
                aligned_image, footprint = aa.register(
                    light.data.byteswap().newbyteorder(),
                    ref_im.data.byteswap().newbyteorder(),
                    detection_sigma=3)
            except aa.MaxIterError:
                print(f'Error in alignment:{file_name}')

            aligned_light.data = aligned_image
            aligned_light.meta['aligned'] = True
            aligned_file_name = f'aligned_light_file_{fltr}.fit'
            aligned_light.write(aligned_path / file_name, overwrite=True)
    aligned_images.refresh()

    print('IMAGE ALIGNEMENT: DONE')
    return aligned_path, aligned_images
Пример #3
0
    def test_register(self):
        def compare_image(the_image):
            """Return the fraction of sources found in the reference image"""
            # pixel comparison is not good, doesn't work. Compare catalogs.
            full_algn = the_image.astype("float32")
            import sep

            bkg = sep.Background(full_algn)
            thresh = 3.0 * bkg.globalrms
            allobjs = sep.extract(full_algn - bkg.back(), thresh)
            allxy = np.array([[obj["x"], obj["y"]] for obj in allobjs])

            from scipy.spatial import KDTree

            ref_coordtree = KDTree(self.star_ref_pos)

            # Compare here srcs list with self.star_ref_pos
            num_sources = 0
            for asrc in allxy:
                found_source = ref_coordtree.query_ball_point(asrc, 3)
                if found_source:
                    num_sources += 1
            fraction_found = float(num_sources) / float(len(allxy))
            return fraction_found

        registered_img, footp = aa.register(source=self.image,
                                            target=self.image_ref)
        self.assertIs(type(registered_img), np.ndarray)
        self.assertIs(type(footp), np.ndarray)
        self.assertIs(footp.dtype, np.dtype("bool"))
        fraction = compare_image(registered_img)
        self.assertGreater(fraction, 0.85)
Пример #4
0
def tryregister(path, source, target, sigclip, root, strict=True):
    attempts = 0
    while attempts < 3:
        try:
            aligned = aa.register(source, target)
            hdu = fits.PrimaryHDU(aligned)
            hdul = fits.HDUList([hdu])
            hdr = hdul[0].header

            with fits.open(path) as sci_data:
                hdr['DATE-OBS'] = sci_data[0].header['DATE-OBS']

            filename, _ = splitext(basename(path))
            aligned_fits = root + '/aligned/' + filename + '_aligned.fits'
            hdul.writeto(aligned_fits)
            return aligned, sigclip
        except aa.MaxIterError:
            if strict:
                return np.zeros_like(source), sigclip
            if not strict:
                sigclip += 5
                source = hotpixfix_wrapper(path, sigclip)
                attempts += 1
        except Exception:
            return np.zeros_like(source), sigclip
    return np.zeros_like(source), sigclip
Пример #5
0
 def test_fill_value(self):
     registered_img, footp = aa.register(source=self.image,
                                         target=self.image_ref,
                                         fill_value=-9999.99,
                                         )
     self.assertTrue(all(registered_img[footp] == -9999.99))
     self.assertTrue(all(registered_img[~footp] != -9999.99))
Пример #6
0
 def test_register_ccddata(self):
     ccd_image = CCDData(
         self.image,
         mask=self.image_mask,
         meta={
             "object": "fake galaxy",
             "filter": "R"
         },
         unit="adu",
     )
     ccd_image_ref = CCDData(
         self.image_ref,
         mask=self.image_ref_mask,
         meta={
             "object": "fake galaxy",
             "filter": "R"
         },
         unit="adu",
     )
     registered_img, footp = aa.register(source=ccd_image,
                                         target=ccd_image_ref)
     self.assertIsInstance(registered_img, np.ndarray)
     self.assertIsInstance(footp, np.ndarray)
     self.assertIs(footp.dtype, np.dtype("bool"))
     fraction = self.compare_image(registered_img)
     self.assertGreater(fraction, 0.85)
Пример #7
0
def align_the_images(path,filename,ref_image):



    '''
    This function is meant for alignment of the images with respect to a reference image. To do this task we are using the astro-align package.

    INPUT:

    path: The directory where the images are kept (string)
    filename: The first few characters and the extension of the images (string). Example:
    j0946*fits, HD1104*fits etc.
    ref_image: Reference image which will be used to align the images.

    OUTPUT:

    aligned images.

    '''



    nfiles=sorted(glob(path+filename))
    image_data=fits.open(path+ref_image)
    reference_image=image_data[0].data
    for i in range(len(nfiles)):
        image_data=fits.open(nfiles[i])
        source_image=image_data[0].data
        header=image_data[0].header
        image_aligned,footprint=aa.register(source_image,reference_image)

        aligned_file=nfiles[i].replace('.fits','')
        fits.writeto(aligned_file+'_aligned'+'.fits',image_aligned,header,overwrite=True)

        print('No. %i done'%i)
Пример #8
0
    def _align(self, img: Image) -> Image:
        reference = self.db.get_stacked_image(str(img.key))

        if reference is None:
            logging.info(f"no reference found for {img.key}")
            return img

        assert img.data.dtype == np.float32 and img.data.min() >= 0.0 and img.data.max() <= 1.0, f"{img.data.dtype} {img.data.max()} {img.data.min()}"
        assert reference.data.dtype == np.float32 and reference.data.min() >= 0.0 and reference.data.max() <= 1.0, f"{reference.data.dtype} {reference.data.max()} {reference.data.min()}"
        assert reference.data.ndim == img.data.ndim, f"{reference.data.ndim} {img.data.ndim}"
        assert reference.data.shape == img.data.shape, f"{reference.data.shape} {img.data.shape}"

        with Timer(f"aligning image for {img.key}"):
            if img.data.ndim == 2:
                registered, footprint = aa.register(img.data, reference.data, fill_value=0.0)
                img.data = registered
            elif img.data.ndim == 3:
                transform, _ = aa.find_transform(img.data[0], reference.data[0])

                for i in range(3):
                    transformed, _ = aa.apply_transform(transform, img.data[i], reference.data[i], fill_value=0.0)
                    img.data[i] = transformed
            else:
                raise Exception(f"invalid image dimensions {img.data.ndim}")

        assert img.data.dtype == np.float32 and img.data.min() >= 0.0 and img.data.max() <= 1.0, f"{img.data.dtype} {img.data.max()} {img.data.min()}"

        return img
Пример #9
0
def align(hduls, name="SCI", reference=None):
    """
    Aligns the source astronomical image(s) to the reference astronomical image
    \b
    :param hduls: list of fitsfiles
    :return: list of fistfiles with <name> HDU aligned
    """

    hduls_list = [hdul for hdul in hduls]
    sources = [hdul[name] for hdul in hduls_list]
    outputs = []

    if reference is None:
        reference = snr.snr(hduls_list, name)[name]
    # click.echo(reference.header["ORIGNAME"])
    # FIXME log ref name
    np_ref = to_np(
        reference,
        "Cannot align to unexpected type {}; expected numpy array or FITS HDU")

    for source in sources:
        np_src = to_np(
            source,
            "Cannot align unexpected type {}; expected numpy array or FITS HDU"
        )
        # possibly unneccessary but unsure about scoping
        output = np.array([])

        output = astroalign.register(np_src, np_ref)[0]
        if isinstance(source, HDU_TYPES):
            output = PrimaryHDU(output, source.header)
        outputs.append(HDUList([output]))

    return (hdul for hdul in outputs)
Пример #10
0
 def test_register(self):
     registered_img, footp = aa.register(source=self.image,
                                         target=self.image_ref)
     self.assertIsInstance(registered_img, np.ndarray)
     self.assertIsInstance(footp, np.ndarray)
     self.assertIs(footp.dtype, np.dtype("bool"))
     fraction = self.compare_image(registered_img)
     self.assertGreater(fraction, 0.85)
Пример #11
0
 def test_register_rgba_channels(self):
     "Test register works with RGB images"
     registered, footp = aa.register(source=self.image_rgba_new,
                                     target=self.image_rgba_ref)
     self.assertEqual(registered.ndim, self.image_rgba_new.ndim)
     fraction = self.compare_image(registered)
     self.assertGreater(fraction, 0.70)
     self.assertTrue(footp.ndim == 2)
     self.assertTrue(footp.shape == (self.h, self.w))
Пример #12
0
 def test_register_png_image(self):
     source = Image.open(self.pngnew_fp)
     target = Image.open(self.pngref_fp)
     registered, footp = aa.register(source, target)
     self.assertEqual(registered.ndim, self.image_rgba_new.ndim)
     fraction = self.compare_image(registered)
     self.assertGreater(fraction, 0.70)
     self.assertTrue(footp.ndim == 2)
     self.assertTrue(footp.shape == (self.h, self.w))
Пример #13
0
def align_stars(images,ref=None,hdu=0):
    """
    Pixel align a list of images using astroalign
    
    Parameters
    ----------
    images: list of numpy arrays or list of file names
        List of images to align.

    ref: numpy array or file name, optional
        Image to use as a reference point for alginment, all images
        in the list will be aligned to this image. If none
        the first image in the list will be used.

    hdu: int
        Hdu of data if list of file names is provided. Default is 0.
    
    Returns
    -------
    algined_arrays: numpy array
        List of pixel aligned numpy arrays
    """

    #determine type of input and read data to list if file names
    list_type = type(images[0])
    if list_type is str:
        image_arrays = []
        for f in images:
            with fits.open(f) as fo:
                image_data = fo[hdu].data
            image_arrays.append(np.nan_to_num(image_data).astype(np.float64))
    else:
        image_arrays = [np.nan_to_num(x).astype(np.float64) for x in images]

    #check for a reference image and determine type
    if ref is None:
        ref_array = image_arrays.pop(0)
    else:
        ref_type = type(ref)
        if ref_type is str:
            with fits.open(ref) as fo:
                ref_data = fo[hdu].data
            ref_array = np.nan_to_num(ref_data).astype(np.float64)
        else:
            ref_array = np.nan_to_num(ref).astype(np.float64)

    #align using astroalign
    aligned_arrays = []
    aligned_arrays.append(ref_array)
    for image in image_arrays:
        try:
            aligned, _ = aa.register(image,ref_array)
            aligned_arrays.append(aligned)
        except:
            print('MaxIterError: Max iterations exceeded while trying to find acceptable transformation: image not aligned.' )

    return aligned_arrays
Пример #14
0
 def test_register_npma(self):
     ma_image = np.ma.array(self.image, mask=self.image_mask)
     ma_image_ref = np.ma.array(self.image_ref, mask=self.image_ref_mask)
     registered_img, footp = aa.register(source=ma_image,
                                         target=ma_image_ref)
     self.assertIsInstance(registered_img, np.ndarray)
     self.assertIsInstance(footp, np.ndarray)
     self.assertIs(footp.dtype, np.dtype("bool"))
     fraction = self.compare_image(registered_img)
     self.assertGreater(fraction, 0.85)
Пример #15
0
def main(args):
    imgsdir = '/home/bruno/Documentos/Data/SNiPTF/imgs'
    imgsdir = '/home/bruno/Data/SNiPTF/imgs'

    #imgsdir = '/home/bruno/Documentos/Data/LIGO_O2/20171116/ESO202-009'
    dest_dir = './test/test_images/test_sub_sniptf'
    imgs = glob.glob(imgsdir + '/*sci*.fits')
    mask = glob.glob(imgsdir + '/*mask*.fits')

    imgs.sort()
    mask.sort()

    images = [
        s.SingleImage(animg, mask=amask) for animg, amask in zip(imgs, mask)
    ]

    #images = [s.SingleImage(animg) for animg in imgs]
    for i, animg in enumerate(images[1:]):
        #~ t, _ = aa.find_transform(animg.data, images[0].data)

        #~ if abs(t.rotation)>5e-4:
        #~ k = t.__class__
        #~ t = k(np.round(t.params, decimals=5))

        #~ reg = aa.apply_transform(t, animg.data, images[0].data)
        reg = aa.register(animg.data, images[0].data)
        new = s.SingleImage(reg.data, mask=reg.mask)

        fits.writeto('/home/bruno/aligned_{}.fits'.format(i),
                     reg.data,
                     overwrite=True)

        D, P, S_corr, mask = ps.diff(images[0],
                                     new,
                                     align=True,
                                     iterative=False,
                                     shift=True,
                                     beta=True)

        D = np.ma.MaskedArray(D.real, mask).filled(np.median(D.real))
        fits.writeto(os.path.join(dest_dir, 'Diff_{}.fits'.format(i)),
                     D.real,
                     overwrite=True)
        fits.writeto(os.path.join(dest_dir, 'P_{}.fits'.format(i)),
                     P.real,
                     overwrite=True)
        fits.writeto(os.path.join(dest_dir, 'Scorr_{}.fits'.format(i)),
                     S_corr,
                     overwrite=True)
        new._clean()
    for an_img in images:
        an_img._clean()

    return
Пример #16
0
	def align_objects(self, object_list, output_dir, method):
		"""Align a series of frames to a reference frame via ASTROALIGN or WCS REPROJECTION"""

		if len(object_list) == 0 or len(object_list) == 1:

			print("Insufficient number of images for alignment")

		else:

			print("Opening reference frame", object_list[0])
			reference_frame = fits.open(object_list[0])
			reference_data = reference_frame[0].data
			reference_header = reference_frame[0].header

			print("Converting reference data to FITS")
			reference_hdu = fits.PrimaryHDU(reference_data, header=reference_header)

			print("Writing reference frame to output directory")
			reference_hdu.writeto(output_dir + "/a-" + str(object_list[0]), overwrite=True)

			for i in range(1, len(object_list)):

				if os.path.isfile("a-" + object_list[i]):

					print("Skipping align on", object_list[i])

				else:

					print("Opening target frame", object_list[i])
					target_frame = fits.open(object_list[i])
					target_data = target_frame[0].data
					target_header = target_frame[0].header

					if method == "astroalign":

						print("Aligning target frame with reference frame via ASTROALIGN")
						array = aa.register(target_data, reference_data)

					elif method == "reproject":

						print("Converting target data to FITS")
						target_hdu = fits.PrimaryHDU(target_data, header=target_header)

						print("Aligning target frame with reference frame via WCS")
						array, footprint = reproject_interp(target_hdu, reference_header)

					print("Converting aligned target data to FITS")
					target_hdu = fits.PrimaryHDU(array, header=target_header)

					print("Writing aligned frame to output directory")
					target_hdu.writeto(output_dir + "/a-" + str(object_list[i]), overwrite=True)

		return
Пример #17
0
def align_the_images(path, filename, ref_image):
    nfiles = sorted(glob(path + filename))
    image_data = fits.open(path + ref_image)
    reference_image = image_data[0].data
    for i in range(len(nfiles)):
        image_data = fits.open(nfiles[i])
        source_image = image_data[0].data
        image_aligned, footprint = aa.register(source_image, reference_image)
        fits.writeto(path + 'j0947_corrected_%i.fits' % i,
                     image_aligned,
                     overwrite=True)
        print('No. %i done' % i)
Пример #18
0
def align_with(image, ref_matrix, ref_file):
    """
    Given a FITS file it will open the file and align to the reference image
    matrix and rewrite the file.
    It uses the astroalign package that align stellar astronomical images with
    an 3 point matching (triangle). It need above about 10 stellar sources in
    an image (based on the tests).

    # This function takes the matrix directly (instead of path to file)
    because of performance. This function in meant to be used within a loop,
    with this the ref_matrix needs to be loaded just once.

    Parameters
    ----------
        image : str
            Path to image to align with the reference.
        ref_matrix : Numpy 2D array
            Reference image.
        ref_name : str
            Name of reference FITS file.

    Returns
    -------
        None.

    File transformation:
        Re-write FITS file pointed at image variable with updated header.
    """
    # Loading

    data = fits.getdata(image)
    data = img_as_float32(data)  # Converting to float to avoid scikitimage bug
    # Issue #4525

    header = fits.getheader(image)
    new_image = "a" + image

    # Aligning

    aligned_image = astroalign.register(data, ref_matrix)

    # Re-write file and update header

    header["ALIGNED-TO"] = ref_file

    fits.writeto(new_image, aligned_image, header)
    os.remove(image)
Пример #19
0
def align2(location):
    x = 1
    images = glob.glob(location + "/*_N_.fits")
    ref = glob.glob(location + "/*_ref_A_.fits")
    hdu2 = fits.open(ref[0])
    data2 = hdu2[0].data
    data2 = np.array(data2, dtype="float64")
    print("\n-> Aligning images with astroalign...")
    for i in images:
        worked = True
        hdu1 = fits.open(i)
        data1 = hdu1[0].data
        data1 = np.array(data1, dtype="float64")
#        transf, (source_list, target_list) = astroalign.find_transform(data1, data2)
#        aligned = astroalign.apply_transform(transf, data1, data2)
        try:
            aligned = astroalign.register(data1, data2)
        except:
            view_im = input("\n-> Alignment failed: View trouble image in ds9? (y/n): ")
            if view_im == 'y':
                os.system("ds9 -scale zscale %s" % (i))
            elif view_im == 'n':
                pass
            else:
                print("-> Unknown input: must be y or n")
            delete = input("\n-> Delete trouble image from data set? (Do so if image has obvious issues or artifacts) (y/n): ")
            if delete == 'y':
                os.system("mkdir -p %s/sdi/archive/failed_alignments ; mv %s %s/sdi/archive/failed_alignments" % (loc, i, loc))
                print("\n-> Moved trouble image to 'failed_alignments' in 'archive' directory")
            elif delete == 'n':
                pass
            else:
                print("\n-> Unknown input: must be y or n")
            worked = False
            x += 1
        if worked == True:
            aligned_name = i[:-8] + "_A_.fits"
            hdu = fits.PrimaryHDU(aligned, header=hdu1[0].header)
            hdu.writeto(aligned_name)
            hdu1.close()
            os.system("mv %s %s/sdi/archive/data" % (i, loc))
            percent = float(x)/float(len(images)) * 100
            print("-> %.1f%% aligned..." % (percent))
            x += 1
    hdu2.close()
    
Пример #20
0
    def check_if_register_ok(self, numstars):
        """Helper function to test register with common test code
        for 3, 4, 5, and 6 stars"""
        from skimage.transform import estimate_transform

        if numstars > 6:
            raise NotImplementedError

        # x and y of stars in the ref frame (int's)
        self.star_refx = np.array([100, 120, 400, 400, 200, 200])[:numstars]
        self.star_refy = np.array([150, 200, 200, 320, 210, 350])[:numstars]
        self.num_stars = numstars
        # Fluxes of stars
        self.star_f = np.array(numstars * [700.0])

        (
            self.image,
            self.image_ref,
            self.star_ref_pos,
            self.star_new_pos,
        ) = simulate_image_pair(
            shape=(self.h, self.w),
            translation=(self.x_offset, self.y_offset),
            rot_angle_deg=50.0,
            noise_level=50,
            num_stars=self.num_stars,
            star_refx=self.star_refx,
            star_refy=self.star_refy,
            star_flux=self.star_f,
        )

        aligned, footprint = aa.register(self.image_ref, self.image)

        source = self.star_ref_pos
        dest = self.star_new_pos.copy()
        t_true = estimate_transform("similarity", source, dest)
        aligned_true, fp = aa.apply_transform(t_true, self.image_ref,
                                              self.image)

        err = np.linalg.norm((aligned_true - aligned)[fp], 1) / np.linalg.norm(
            (aligned_true)[fp], 1)
        self.assertLess(err, 1e-1)
Пример #21
0
        def align(self, image, ref, output, overwrite=True):
            """Aligning an image with respect of given referance"""
            self.logger.info("Aligning image({}) with reference({})".format(
                image, ref))
            try:
                image_data = self.data(image)
                image_header = self.header(image, field="?")

                ref_data = self.data(ref)

                img_aligned, _ = aa.register(image_data, ref_data)

                self.write(output,
                           img_aligned,
                           header=image_header,
                           overwrite=overwrite)
                return True
            except Exception as e:
                self.logger.error(e)
                return False
Пример #22
0
def align3(location):
    x = 1
    images = glob.glob(location + "/data/*_A_.fits")
    temp = glob.glob(location + "/templates/*.fits")
    hdu2 = fits.open(temp[0])
    data2 = hdu2[0].data
    data2 = np.array(data2, dtype="float64")
    for i in images:
        hdu1 = fits.open(i)
        data1 = hdu1[0].data
        data1 = np.array(data1, dtype="float64")
        aligned = astroalign.register(data1, data2)
        aligned_name = i[:-8] + "_AT_.fits"
        hdu = fits.PrimaryHDU(aligned, header=hdu1[0].header)
        hdu.writeto(aligned_name)
        hdu1.close()
        percent = float(x) / float(len(images)) * 100
        print("%.3f%% aligned..." % (percent))
        x += 1
    hdu2.close()
Пример #23
0
def align2(location):
    x = 1
    images = glob.glob(location + "/*_N_.fits")
    ref = glob.glob(location + "/*_ref_A_.fits")
    hdu2 = fits.open(ref[0])
    data2 = hdu2[0].data
    data2 = np.array(data2, dtype="float64")
    for i in images:
        hdu1 = fits.open(i)
        data1 = hdu1[0].data
        data1 = np.array(data1, dtype="float64")
        #        transf, (source_list, target_list) = astroalign.find_transform(data1, data2)
        #        aligned = astroalign.apply_transform(transf, data1, data2)
        aligned = astroalign.register(data1, data2)
        aligned_name = i[:-8] + "_A_.fits"
        hdu = fits.PrimaryHDU(aligned, header=hdu1[0].header)
        hdu.writeto(aligned_name)
        hdu1.close()
        os.system("mv %s %s/sdi/archive/data" % (i, loc))
        percent = float(x) / float(len(images)) * 100
        print("%.1f%% aligned..." % (percent))
        x += 1
    hdu2.close()
Пример #24
0
def align(hduls, name="SCI", reference=None):
    """
    Aligns the source astronomical image(s) to the reference astronomical image
    \b
    :param hduls: list of fitsfiles
    :return: list of fistfiles with <name> HDU aligned
    """

    hduls_list = [hdul for hdul in hduls]
    sources = [hdul[name] for hdul in hduls_list]
    outputs = []

    if reference is None:
        reference = snr.snr(hduls_list, name)[name]
    # click.echo(reference.header["ORIGNAME"])
    # FIXME log ref name
    np_ref = reference
    try:
        np_ref = np_ref.data
    except AttributeError:
        pass

    for source in sources:
        np_src = source
        try:
            np_src = source.data
        except AttributeError:
            pass
        # possibly unneccessary but unsure about scoping
        output = np.array([])

        output = astroalign.register(np_src, np_ref)[0]
        if hasattr(source, "data"):
            output = PrimaryHDU(output, source.header)
        outputs.append(HDUList([output]))

    return (hdul for hdul in outputs)
Пример #25
0
def registra_lista(lista):
    cantidad = len(lista)

    # La primera imagen de la lista será la toma de referencia.
    print("\nComenzando la alineación.")
    print("\nLa toma de referencia es {:}".format(lista[0]))
    blanco = ft.open(lista[0])
    img_blanco = blanco[0].data
    hdr_blanco = blanco[0].header
    blanco.close()
    del (lista[0])  # Quito la imagen de referencia del listado
    for ii in lista:
        ff = ft.open(ii)
        img_torcida = ff[0].data
        hdr_torcida = ff[0].header
        ff.close()
        p, (pos_img,
            pos_img_rot) = astroalign.find_transform(img_torcida, img_blanco)
        imprimir_info(p, ii)
        img_aligned = astroalign.register(img_torcida, img_blanco)
        hdr_torcida.add_comment("Registrado con Astroalign y PyReduc")
        ft.writeto(ii, img_aligned, header=hdr_torcida, overwrite=True)

    print("\nRegistrado realizado con éxito")
Пример #26
0
 def test_dtypes(self):
     # aa.register(self.image.astype('float16'), self.image_ref)
     aa.register(self.image.astype("float32"), self.image_ref)
     aa.register(self.image.astype("float64"), self.image_ref)
     aa.register(self.image.astype("int32"), self.image_ref)
     aa.register(self.image.astype("int64"), self.image_ref)
Пример #27
0
    def test_register(self):
        def compare_image(the_image):
            """Return the fraction of sources found in the reference image"""
            # pixel comparison is not good, doesn't work. Compare catalogs.
            if isinstance(the_image, np.ma.MaskedArray):
                full_algn = the_image.filled(fill_value=np.median(the_image))\
                    .astype('float32')
            else:
                full_algn = the_image.astype('float32')
            # full_algn[the_image == 0] = np.median(the_image)
            import sep
            bkg = sep.Background(full_algn)
            thresh = 3.0 * bkg.globalrms
            allobjs = sep.extract(full_algn - bkg.back(), thresh)
            allxy = np.array([[obj['x'], obj['y']] for obj in allobjs])

            from scipy.spatial import KDTree
            ref_coordtree = KDTree(self.star_ref_pos)

            # Compare here srcs list with self.star_ref_pos
            num_sources = 0
            for asrc in allxy:
                found_source = ref_coordtree.query_ball_point(asrc, 3)
                if found_source:
                    num_sources += 1
            fraction_found = float(num_sources) / float(len(allxy))
            return fraction_found

        registered_img = aa.register(source=self.image,
                                     target=self.image_ref)

        # Test that image returned is not masked
        self.assertIs(type(registered_img), np.ndarray)
        fraction = compare_image(registered_img)
        self.assertGreater(fraction, 0.85)

        # Test masked arrays
        # Make some masks...
        mask = np.zeros(self.image.shape, dtype='bool')
        mask[self.h // 10:self.h // 10 + 10, :] = True
        mask_ref = np.zeros(self.image_ref.shape, dtype='bool')
        mask_ref[:, self.w // 10:self.w // 10 + 10] = True
        image_masked = np.ma.array(self.image, mask=mask)
        image_ref_masked = np.ma.array(self.image_ref, mask=mask_ref)

        def testalignment(source, target):
            registered_img = aa.register(source=source, target=target)
            self.assertIs(type(registered_img), type(source))
            fraction = compare_image(registered_img)
            self.assertGreater(fraction, 0.85)

        # Test it works with masked image:
        testalignment(image_masked, self.image_ref)

        # Test it works with masked ref:
        testalignment(self.image, image_ref_masked)

        # Test it works with both masked image and masked ref:
        testalignment(image_masked, image_ref_masked)

        # Test it works when given a masked array with no mask set
        testalignment(np.ma.array(self.image), self.image_ref)

        # Test it works when given a reference masked array with no mask set
        testalignment(self.image, np.ma.array(self.image_ref))

        # Test if it works when both images are masked, but with no mask set
        testalignment(np.ma.array(self.image), np.ma.array(self.image_ref))
Пример #28
0
 def testalignment(source, target):
     registered_img = aa.register(source=source, target=target)
     self.assertIs(type(registered_img), type(source))
     fraction = compare_image(registered_img)
     self.assertGreater(fraction, 0.85)
Пример #29
0
def image(source_s, reference=None, method="astroalign"):
    """
    Aligns the source astronomical image(s) to the reference astronomical image
    ARGUMENTS
        source_s -- the image(s) to align; fitsio HDU object, numpy array,
            or a list of either one of the above
    KEYWORD ARGUMENTS
        reference -- the image against which to align the source image;
            fitsio HDU object or numpy array. If None, the best option is chosen
            from among the sources.
        method -- the library to use to align the images. options are:
            astroalign (default), skimage, imreg, skimage, chi2
    RETURNS
        a transformed copy of the source image[s] in the same data type
        which was passed in
    """
    # make sure that we can handle source as a list
    sources = []
    outputs = []
    if isinstance(source_s, list):
        sources = source_s
    else:
        sources.append(source_s)

    if reference is None:
        reference = ref_image(sources)
    print(reference.header["ORIGNAME"])
    np_ref = to_np(
        reference,
        "Cannot align to unexpected type {}; expected numpy array or FITS HDU")

    for source in sources:
        np_src = to_np(
            source,
            "Cannot align unexpected type {}; expected numpy array or FITS HDU"
        )
        # possibly unneccessary but unsure about scoping
        output = np.array([])

        if method == "astroalign":
            try:
                output = astroalign.register(np_src, np_ref)[0]
            except NameError:
                raise ValueError(DISABLED.format(method, "astroalign"))
        elif method == "skimage":
            try:
                shift = register_translation(np_ref, np_src, 100)[0]
                output_fft = fourier_shift(np.fft.fftn(np_src), shift)
                output = np.fft.ifftn(output_fft)
            except NameError:
                raise ValueError(DISABLED.format(method, "scipy or numpy"))
        elif method == "chi2":
            try:
                dx, dy = chi2_shift(np_ref, np_src, upsample_factor='auto')[:2]
                output = fft_tools.shift.shiftnd(data, (-dx, -dy))
            except NameError:
                raise ValueError(DISABLED.format(method, "image_registration"))
        elif method == "imreg":
            try:
                output = imreg_dft.similarity(np_ref, np_src)["timg"]
            except NameError:
                raise ValueError(DISABLED.format(method, "imreg_dft"))
        else:
            raise ValueError("Unexpected alignment method {}!".format(method))

        if isinstance(source, HDU_TYPES):
            output = PrimaryHDU(output, source.header)
        outputs.append(output)

    return outputs if isinstance(source_s, list) else outputs[0]
Пример #30
0
rband_filepath = '../M82_r-band_120s_bin1_210126_052734_itzamna_seo_0_RAW.fits'

rband_fits = fits.open(rband_filepath, do_not_scale_image_data=False)
halpha_fits = fits.open(halpha_filepath, do_not_scale_image_data=False)

rband16 = rband_fits[0].data
halpha16 = halpha_fits[0].data

rband8Rgb1 = cv2.cvtColor(rband16, cv2.COLOR_BayerGB2RGB)
halpha8Rgb1 = cv2.cvtColor(halpha16, cv2.COLOR_BayerGB2RGB)
cv2.imwrite('source.png', rband8Rgb1)
cv2.imwrite('target.png', halpha8Rgb1)

# for reference: aa.register(source, target)
# we are transforming the broadband image to match the narrowband
registered, footprint = aa.register(rband8Rgb1, halpha8Rgb1)

# some opencv magic to clean up the image
registered = cv2.normalize(registered,
                           None,
                           0,
                           255,
                           cv2.NORM_MINMAX,
                           dtype=cv2.CV_8U)

# save file
cv2.imwrite(OUTPUTFILE, np.uint8(registered))

# get transformation data for the hell of it
p, (pos_img, pos_img_rot) = aa.find_transform(rband8Rgb1, halpha8Rgb1)
print("Rotation: {:.2f} degrees".format(p.rotation * 180.0 / np.pi))