Example #1
0
    def preprocess(self, image, dr):
        filter_name = image.get_keyword('FILTER01').strip().upper()
        ccd_id = int(image.get_keyword('DET-ID'))

        dr.remove_overscan(image, sub_bias=self.sub_bias)

        if self.use_flat:
            # flat field this piece, if flat provided
            if filter_name != self.flat_filter:
                self.log("Change of filter detected--resetting flats")
                self.flat = {}
                self.flat_filter = filter_name

            try:
                if not ccd_id in self.flat:
                    self.load_flat(ccd_id, filter_name)

                flat = self.flat[ccd_id]

                data_np = image.get_data()
                if data_np.shape == flat.shape:
                    data_np /= flat

                else:
                    raise ValueError("flat for CCD %d shape %s does not match image CCD shape %s" % (ccd_id, flat.shape, data_np.shape))

                header = {}
                image = dp.make_image(data_np, image, header)

            except Exception as e:
                self.logger.warning("Error applying flat field: %s" % (str(e)))

        return image
Example #2
0
    def create_mask(self):
        """Create boolean mask from drawing.

        All areas enclosed by all the shapes drawn will be set to 1 (True)
        in the mask. Otherwise, the values will be set to 0 (False).
        The mask will be inserted as a new image buffer, like ``Mosaic``.

        """
        ntags = len(self._drawn_tags)

        if ntags == 0:
            return

        old_image = self.fitsimage.get_image()

        if old_image is None:
            return

        mask = None
        obj_kinds = set()

        # Create mask
        for tag in self._drawn_tags:
            obj = self.canvas.get_object_by_tag(tag)

            try:
                cur_mask = old_image.get_shape_mask(obj)
            except Exception as e:
                self.logger.error('Cannot create mask: {0}'.format(str(e)))
                continue

            if mask is not None:
                mask |= cur_mask
            else:
                mask = cur_mask

            obj_kinds.add(obj.kind)

        # Might be useful to inherit header from displayed image (e.g., WCS)
        # but the displayed image should not be modified.
        # Bool needs to be converted to int so FITS writer would not crash.
        image = dp.make_image(mask.astype('int16'),
                              old_image, {},
                              pfx=self._mask_prefix)
        imname = image.get('name')

        # Insert new image
        self.fv.gui_call(self.fv.add_image, imname, image, chname=self.chname)

        # This sets timestamp
        image.make_callback('modified')

        # Add change log to ChangeHistory
        s = 'Mask created from {0} drawings ({1})'.format(
            ntags, ','.join(sorted(obj_kinds)))
        iminfo = self.channel.get_image_info(imname)
        iminfo.reason_modified = s
        self.logger.info(s)
Example #3
0
    def create_mask(self):
        """Create boolean mask from drawing.

        All areas enclosed by all the shapes drawn will be set to 1 (True)
        in the mask. Otherwise, the values will be set to 0 (False).
        The mask will be inserted as a new image buffer, like ``Mosaic``.

        """
        ntags = len(self._drawn_tags)

        if ntags == 0:
            return

        old_image = self.fitsimage.get_image()

        if old_image is None:
            return

        mask = None
        obj_kinds = set()

        # Create mask
        for tag in self._drawn_tags:
            obj = self.canvas.get_object_by_tag(tag)

            try:
                cur_mask = old_image.get_shape_mask(obj)
            except Exception as e:
                self.logger.error('Cannot create mask: {0}'.format(str(e)))
                continue

            if mask is not None:
                mask |= cur_mask
            else:
                mask = cur_mask

            obj_kinds.add(obj.kind)

        # Might be useful to inherit header from displayed image (e.g., WCS)
        # but the displayed image should not be modified.
        # Bool needs to be converted to int so FITS writer would not crash.
        image = dp.make_image(mask.astype('int16'), old_image, {},
                              pfx=self._mask_prefix)
        imname = image.get('name')

        # Insert new image
        self.fv.gui_call(self.fv.add_image, imname, image, chname=self.chname)

        # This sets timestamp
        image.make_callback('modified')

        # Add change log to ChangeHistory
        s = 'Mask created from {0} drawings ({1})'.format(
            ntags, ','.join(sorted(obj_kinds)))
        iminfo = self.channel.get_image_info(imname)
        iminfo.reason_modified = s
        self.logger.info(s)
Example #4
0
 def skysub(self):
     firstdat = self.niimage.get_data()
     seconddat = self.nisky.get_data()
     finaldat = firstdat - seconddat
     final_image = dp.make_image(finaldat,
                                 self.niimage, {},
                                 pfx='subtracted')
     name = dp.get_image_name(final_image)
     self.fv.add_image(name, final_image, chname='Image')
Example #5
0
 def subimg(self):
     first = self.fv.load_file(self.w.first.get_text(), chname = '1')
     second = self.fv.load_file(self.w.second.get_text(), chname = '2')
     firstdat = first.get_data()
     seconddat = second.get_data()
     finaldat = firstdat - seconddat
     final_image = dp.make_image(finaldat, first, {}, pfx='subtracted')
     name = dp.get_image_name(final_image)
     self.fv.add_image(name, final_image, chname='4')
Example #6
0
    def mangle_image(self, image):
        d = self.dr.get_regions(image)
        header = {}
        data_np = image.get_data()

        # subtract overscan region
        result = self.dr.subtract_overscan_np(data_np, d,
                                              header=header)

        # flat field this piece, if flat provided
        do_flat = self.w.use_flats.get_state()
        if do_flat and (len(self.flat) > 0):
            try:
                ccd_id = int(image.get_keyword('DET-ID'))
                result /= self.flat[ccd_id]
            except Exception as e:
                self.logger.warn("Error applying flat field: %s" % (str(e)))

        newimage = dp.make_image(result, image, header)
        return newimage
Example #7
0
 def run_cb(self):
     ra_deg1 = 0.5
     dec_deg1 = 0.5
     fov_deg1 = 0.2
     rot_deg1 = 0.0
     cdelt11 = -2.0
     cdelt21 = 1.0
     px_scale1 = math.fabs(cdelt11)
     cdbase1 = [np.sign(cdelt11), np.sign(cdelt21)]
     blankim = dp.create_blank_image(ra_deg1, dec_deg1,
                                   fov_deg1, px_scale1, rot_deg1,
                                   cdbase=cdbase1,
                                   logger=None)
     blankdat = np.array([[0 for x in range(100)] for y in range(100)])
     finalblank = dp.make_image(blankdat, blankim, {}, pfx='mosaic')
     self.fv.add_image('Initial', finalblank, chname='Mosaic') 
     self.cachedFiles = None
     self.cachedFiles = self.walkDirectory();
     self.thread = None
     self.runThread = True
     print("Scan started...")
     self.scan(timeout=200)
Example #8
0
    def multimos(self, filename):
        hdulist = fits.open(filename)
        files = np.sum([
            1 for hdu in hdulist if
            type(hdu) in [fits.hdu.image.PrimaryHDU, fits.hdu.image.ImageHDU]
            and hdu.data is not None
        ])
        k = 0
        j = 0

        ra_deg = 0.5
        dec_deg = 0.5
        fov_deg = 0.2
        header = hdulist[1].header
        (rot_deg, cdelt1,
         cdelt2) = wcs.get_rotation_and_scale(header, skew_threshold=1)
        px_scale = math.fabs(cdelt1)
        cdbase = [np.sign(cdelt1), np.sign(cdelt2)]

        ###Sorting Images###
        imagesort = [[0 for x in range(4)] for y in range(files)]
        for i in range(1, files + 1):
            imagesort[i - 1][0] = hdulist[i]
            df = hdulist[i].header['DETSEC']
            cpos = df.index(':')
            epos = df.index(',')
            dflow = ''.join(df[1:cpos])
            dflow = int(dflow)
            dfhigh = ''.join(df[cpos + 1:epos])
            dfhigh = int(dfhigh)
            imagesort[i - 1][1] = dflow + dfhigh
            ncpos = df.index(':', cpos + 1)
            nepos = df.index(']')
            yflow = ''.join(df[epos + 1:ncpos])
            yflow = int(yflow)
            yhigh = ''.join(df[ncpos + 1:nepos])
            yhigh = int(yhigh)
            imagesort[i - 1][2] = yflow + yhigh
            ccd = hdulist[i].header['CCDNAME']
            imagesort[i - 1][3] = ccd

        sortedim = sorted(imagesort, key=lambda x: x[1])

        ###Putting images together###

        #2D#

        if sortedim[0][1] == sortedim[1][1]:
            for i in range(1, files + 1):
                dr = sortedim[i - 1][0].header['DATASEC']
                colpos = dr.index(':')
                endpos = dr.index(',')
                drlow = ''.join(dr[1:colpos])
                drlow = int(drlow)
                drhigh = ''.join(dr[colpos + 1:endpos])
                drhigh = int(drhigh)
                imdata = sortedim[i - 1][0].data[:, drlow:drhigh]
                gapxdim = np.size(imdata, 0)
                gapx = np.zeros((gapxdim, 30))
                gapx[:, :] = np.nan
                gapydim = np.size(imdata, 1) + 30
                gapy = np.zeros((20, gapydim))
                gapy[:, :] = np.nan
                fgapy = np.zeros((20, gapydim - 30))
                fgapy[:, :] = np.nan
                #image flips#
                df = sortedim[i - 1][0].header['DETSEC']
                cpos = df.index(':')
                epos = df.index(',')
                dflow = ''.join(df[1:cpos])
                dflow = int(dflow)
                dfhigh = ''.join(df[cpos + 1:epos])
                dfhigh = int(dfhigh)
                ncpos = df.index(':', cpos + 1)
                nepos = df.index(']')
                yflow = ''.join(df[epos + 1:ncpos])
                yflow = int(yflow)
                yhigh = ''.join(df[ncpos + 1:nepos])
                yhigh = int(yhigh)
                if dflow > dfhigh:
                    findatx = np.fliplr(imdata)
                else:
                    findatx = imdata

                if yflow > yhigh:
                    findat = np.flipud(findatx)
                else:
                    findat = findatx
                fm = files - 1
                if i != files:
                    if i != fm:
                        if sortedim[i - 1][3] != sortedim[i][3]:
                            findat = np.column_stack((findat, gapx))

                if i == 1:
                    vert = findat

                elif sortedim[i - 1][1] == sortedim[i - 2][1]:
                    if sortedim[i - 1][2] > sortedim[i - 2][2]:
                        if i == files:
                            vert = np.vstack((vert, fgapy))
                            vert = np.vstack((vert, findat))
                            if i == files:
                                final = np.column_stack((final, vert))
                        else:
                            vert = np.vstack((vert, gapy))
                            vert = np.vstack((vert, findat))
                            if i == files:
                                final = np.column_stack((final, vert))
                    else:
                        findat = np.vstack((findat, gapy))
                        vert = np.vstack((findat, vert))
                        if i == files:
                            final = np.column_stack((final, vert))

                else:
                    k = k + 1
                    if k == 1:
                        final = vert
                        vert = findat
                    else:
                        final = np.column_stack((final, vert))
                        vert = findat

        else:
            #1d#
            for i in range(1, files + 1):
                #data ranges#
                dr = sortedim[i - 1][0].header['DATASEC']
                colpos = dr.index(':')
                endpos = dr.index(',')
                drlow = ''.join(dr[1:colpos])
                drlow = int(drlow)
                drhigh = ''.join(dr[colpos + 1:endpos])
                drhigh = int(drhigh)
                imdata = sortedim[i - 1][0].data[:, drlow:drhigh]
                gapxdim = np.size(imdata, 0)
                gapx = np.zeros((gapxdim, 30))
                gapx[:, :] = np.nan
                #image flips#
                df = sortedim[i - 1][0].header['DETSEC']
                cpos = df.index(':')
                epos = df.index(',')
                dflow = ''.join(df[1:cpos])
                dflow = int(dflow)
                dfhigh = ''.join(df[cpos + 1:epos])
                dfhigh = int(dfhigh)
                ncpos = df.index(':', cpos + 1)
                nepos = df.index(']')
                yflow = ''.join(df[epos + 1:ncpos])
                yflow = int(yflow)
                yhigh = ''.join(df[ncpos + 1:nepos])
                yhigh = int(yhigh)

                if dflow > dfhigh:
                    findatx = np.fliplr(imdata)
                else:
                    findatx = imdata

                if yflow > yhigh:
                    findat = np.flipud(findatx)
                else:
                    findat = findatx
                #final image
                if i == 1:
                    final = findat
                else:
                    final = np.append(final, findat, axis=1)

                if i != files and sortedim[i - 1][3] != sortedim[i][3]:
                    final = np.append(final, gapx, axis=1)

        #finalimage#
        #plt.imshow(final)
        #plt.show()
        #finalimage = fits.ImageHDU()
        #finalimage.data = final
        oldim = dp.create_blank_image(ra_deg,
                                      dec_deg,
                                      fov_deg,
                                      px_scale,
                                      rot_deg,
                                      cdbase=cdbase,
                                      logger=None)
        finalimage = dp.make_image(final, oldim, {}, pfx='mosaic')
        name = dp.get_image_name(finalimage)
        self.fv.add_image(name, finalimage, chname='Mosaic')