Пример #1
0
def display_map(map, scale="logZscale"):
    img = fits.open(map)[0]
    image_data = img.data[:, :]
    image_data = img.data[:, :] / np.mean(image_data)
    for i, line in enumerate(image_data):
        for j, col in enumerate(line):
            image_data[i][j] = max([col, 0.00001])

    print len(image_data)
    #image_data= image_data/((1-0.72)**2-1.03**2)
    fig, ax = plt.subplots(1, figsize=(10, 10))
    ax.set_aspect('equal')

    if scale == "linZscale":
        norm = ImageNormalize(image_data,
                              interval=ZScaleInterval(contrast=0.01),
                              stretch=SqrtStretch())

        im = ax.imshow(image_data, cmap='gray', norm=norm)
        plt.colorbar(im, ax=ax)

    if scale == "logZscale":
        new_image_data = 2.5 * np.log(image_data)
        norm = ImageNormalize(new_image_data,
                              interval=ZScaleInterval(contrast=0.000001),
                              stretch=SqrtStretch())
        im = ax.imshow(new_image_data - np.min(new_image_data),
                       aspect='auto',
                       cmap='gray')
        #plt.colorbar(im,ax=ax)

    circ = Circle((1000, 3000), 20, ec="red", fc=None, fill=False)
    circ2 = Circle((1000, 3000), 250, ec="green", fc=None, fill=False)
    #ax.add_patch(circ)
    #ax.add_patch(circ2)
    #plt.axis('off')
    locs2 = ax.get_xticks()
    print locs2
    # locs2[1] = frequency_spline[0]
    temp_lab = ax.get_xticklabels()

    lab2 = np.round(np.multiply(0.00244140625, locs2[1:-1]), 1)
    print lab2
    labels = []
    ax.set(xlabel=r'$\theta_E$', ylabel=r'$\theta_E$')
    ax.set_xticks(locs2[1:-1], minor=False)
    ax.set_yticks(locs2[1:-1], minor=False)
    ax.set_xticklabels(lab2, minor=False)
    ax.set_yticklabels(lab2, minor=False)
    plt.show()
    fig.savefig('mapA-B.png')
Пример #2
0
 def norm_set(self, text):
     stretch_dict = {
         'No Stretch': None,
         'Sqrt Stretch': SqrtStretch(),
         'Linear Stretch': LinearStretch(),
         'Squared Stretch': SquaredStretch(),
         'Power Stretch': PowerStretch(self.a),
         'Log Stretch': LogStretch(self.a)
     }
     self.stretch_val = stretch_dict[text]
     if text == 'Log Stretch':
         self.var_max = 10000
         self.var_int = 10
         self.cube = self.stretch_val(self.cube_base)
         #self.norm = ImageNormalize(interval=self.interval, stretch=self.stretch_val, clip=True)
     elif text == 'Sqrt Stretch':
         self.cube = np.sqrt(self.cube)
     elif text == 'No Stretch':
         self.norm = None
         self.cube = self.cube_base
     else:
         self.var_max = 10
         self.var_int = 1
         self.cube = self.stretch_val(self.cube_base, clip=False)
         #self.norm = ImageNormalize(interval=self.interval, stretch=self.stretch_val, clip=True)
     main.create_image(self.cube)
Пример #3
0
def try_dao(fitsfile, outfile='out.png'):

    hdulist = fits.open(fitsfile)
    hdu = hdulist[0]

    if len(hdu.data.shape) == 3:
        data = hdu.data[0]
    else:
        data = hdu.data

    mean, median, std = sigma_clipped_stats(data[800:900, 800:900],
                                            sigma=3.0,
                                            iters=5)
    print(mean, median, std)

    #data = hdu.data
    sources = daofind(data - median, fwhm=3.0, threshold=5. * std)
    print 'Found %i sources' % len(sources)

    positions = (sources['xcentroid'], sources['ycentroid'])
    apertures = CircularAperture(positions, r=4.)
    norm = ImageNormalize(stretch=SqrtStretch(), vmin=2000, vmax=3000)
    plt.imshow(data, cmap='Greys', origin='lower', norm=norm)
    plt.title('%i Sources from a single all-sky frame' % len(sources))
    apertures.plot(color='blue', lw=1.5, alpha=0.5)
    plt.savefig(filename=outfile)
Пример #4
0
    def crop_roi(self,
                 fits_file,
                 source_x,
                 source_y,
                 roi_box=10,
                 use_pil=False):
        body_path, ext = os.path.splitext(fits_file)

        fo = FitsOps(fits_file)

        source_roi = fo.hdu[0].data[int(source_y - roi_box):int(source_y +
                                                                roi_box),
                                    int(source_x - roi_box):int(source_x +
                                                                roi_box)]

        norm = ImageNormalize(stretch=SqrtStretch())
        plt.axis('off')
        plt.imshow(source_roi, cmap='Greys', origin='lower', norm=norm)
        plt.savefig('{}_roi.png'.format(body_path),
                    bbox_inches='tight',
                    pad_inches=0,
                    transparent=True)
        plt.close()

        return source_roi
Пример #5
0
    def stretchImage(self, image=None):
        """
        stretchImage take the actual image and calculated norm based on the min, max
        derived from interval which is calculated with AsymmetricPercentileInterval.

        :param image: image
        :return: norm for plot
        """

        if image is None:
            return None

        values = self.stretchValues[self.ui.stretch.currentText()]
        interval = AsymmetricPercentileInterval(*values)
        vmin, vmax = interval.get_limits(image)
        # cutout the noise
        delta = vmax - vmin
        vmin = min(vmin + delta * 0.01, vmax)

        norm = ImageNormalize(image,
                              vmin=vmin,
                              vmax=vmax,
                              stretch=SqrtStretch(),
                              )

        return norm, vmin, vmax
Пример #6
0
    def plot_frames(self, save=False):
        """ Loop through all the images in a directory and plot them.
        * NEEDS WORK -- NOT DONE *
        """

        image_directory = self.file_list
        self.norm = ImageNormalize(vmin=-300, vmax=22000, stretch=SqrtStretch())

        fig = plt.figure()  # Get a figure up there
        for ip in image_directory:
            plt.plot(i)
        plt.show()
        plt.xlim(1500, 1550)
        plt.ylim(970, 1020)
        ax = fig.add_subplot(111)  # yeah
        ax.set_title("yep")

        im = ax.imshow(self.reduced_images[0], cmap='gray', norm=self.norm, origin='lower')
        fig.show()
        im.axes.figure.canvas.draw()

        for files in image_directory:
            dat = fits.getdata(files, ext=0)
            ax.set_title(str(files))
            im.set_data(dat)
            if save:
                plt.savefig("C:/Users/Austin/Desktop/Nanohmics/fits_images/uh.png", bbox_inches='tight')
            im.axes.figure.canvas.draw()
Пример #7
0
def photplots(data, bkg_image, bkg_rms, data_sub, fitsfile, outfig):
    from astropy.visualization import LogStretch, SqrtStretch
    from astropy.visualization.mpl_normalize import ImageNormalize
    norm = ImageNormalize(stretch=SqrtStretch())
    # for plotting
    mask = (data <= 0)
    data[mask] = 0
    data_sub[mask] = 0
    kw = {'norm': norm, 'cmap': 'Greys', 'origin': 'lower'}
    # kw = {'cmap': 'Greys_r', 'origin': 'lower'}
    bkw = {'cmap': 'Greys_r', 'origin': 'lower'}
    fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(10, 10))
    [ax.grid() for ax in axs.ravel()]
    im = axs[0][0].imshow(data, **kw)
    axs[0][0].set_title(fitsfile)

    im = axs[1][0].imshow(bkg_image, **bkw)
    axs[1][0].set_title('bg')

    im = axs[1][1].imshow(bkg_rms, **bkw)
    axs[1][1].set_title('bg rms')

    # plot background-subtracted image
    ax = axs[0][1]
    im = ax.imshow(data_sub, **kw)
    ax.set_title('bg-sub data')
    plt.tight_layout()
    plt.savefig(outfig)
    return axs
Пример #8
0
def showNorm(imaOrCcd, **kwargs):
    from astropy.visualization import imshow_norm, SqrtStretch
    from astropy.visualization.mpl_normalize import PercentileInterval
    from astropy.nddata import CCDData

    plt.clf()
    fig = plt.gcf()
    if isinstance(imaOrCcd, CCDData):
        arr = imaOrCcd.data
        wcs = imaOrCcd.wcs
        if wcs is None:
            ax = plt.subplot()
        else:
            ax = plt.subplot(projection=wcs)
            ax.coords.grid(True, color='white', ls='solid')
    else:
        arr = imaOrCcd
        ax = plt.subplot()
    if 'interval' not in kwargs:
        kwargs['interval'] = PercentileInterval(99.7)
    if 'stretch' not in kwargs:
        kwargs['stretch'] = SqrtStretch()
    if 'origin' not in kwargs:
        kwargs['origin'] = 'lower'

    im, _ = imshow_norm(arr, ax=ax, **kwargs)

    cb = fig.colorbar(im)
    cb.ax.tick_params(labelsize=11)
Пример #9
0
def display_trajectory_bis(arrow_coord, map):
    arrow = [
        arrow_coord[0], arrow_coord[1],
        int(arrow_coord[2] - arrow_coord[0]), arrow_coord[3] - arrow_coord[1]
    ]
    print arrow
    image_file = get_pkg_data_filename(map)
    image_data = fits.getdata(image_file, ext=0)
    #    image_data = np.swapaxes(image_data,0,1)
    real_arrow = [
        arrow_coord[0], arrow_coord[1], arrow_coord[2], arrow_coord[3]
    ]
    new_image_data = -2.5 * np.log(abs(image_data))
    norm = ImageNormalize(new_image_data - np.min(new_image_data),
                          interval=ZScaleInterval(contrast=0.25),
                          stretch=SqrtStretch())
    im = plt.imshow(new_image_data - np.min(new_image_data),
                    aspect='auto',
                    cmap='gray')
    plt.colorbar(im)

    plt.arrow(arrow[0],
              arrow[1],
              arrow[2],
              arrow[3],
              head_width=50,
              head_length=50,
              fc='g',
              ec='g')
    plt.show()
Пример #10
0
    def get_norm(self, stretch_text, scale_text):

        image = self.ax.get_images()[0]
        scale = None

        if scale_text == "MinMax":
            scale = MinMaxInterval()

        else:
            scale = ZScaleInterval()

        if stretch_text == "Linear":
            stretch = LinearStretch()

        elif stretch_text == "Log":
            stretch = LogStretch()

        else:
            stretch = SqrtStretch()

        minV, maxV = scale.get_limits(
            self.cubeObj.data_cube[self.cubeObj.currSlice])

        norm = ImageNormalize(vmin=minV, vmax=maxV, stretch=stretch)

        return norm
Пример #11
0
def plot_image(fitsname,
               imagename,
               rms=np.nan,
               vmin=-3,
               vmax=25,
               ra_zoom=None,
               dec_zoom=None,
               d_zoom=None,
               AR=16 / 9.):
    '''
    make an image called imagename from cutout from fits file fitsname at coords ra_zoom, dec_zoom and dimensions d_zoom x d_zoom/AR
    '''

    hdu = extract_subim(fitsname, ra_zoom, dec_zoom, d_zoom, d_zoom / AR)

    dat = hdu[0].data
    figsize = (10, 10. / AR)
    f1 = plt.figure(figsize=figsize)

    norm = ImageNormalize(vmin=vmin * rms,
                          vmax=vmax * rms,
                          stretch=SqrtStretch())
    plt.imshow(dat, origin='lower', cmap=plt.cm.cubehelix, norm=norm)

    plt.subplots_adjust(left=0.0, bottom=0.0, top=1.0, right=1.0)

    plt.savefig(imagename)

    return
Пример #12
0
def saveim_png(data,
               savedir,
               fname,
               colmap='coolwarm',
               orig=None,
               datextent=None,
               interp='None',
               xtag='X',
               ytag='Y',
               title=None):

    # Show and save image
    plt.figure()
    norm = ImageNormalize(stretch=SqrtStretch())
    plt.imshow(data,
               cmap=colmap,
               origin=orig,
               norm=norm,
               interpolation=interp,
               extent=datextent)
    plt.colorbar()
    plt.xlabel(xtag, fontsize=20), plt.ylabel(ytag, fontsize=20)
    if not title == None:
        plt.title(title, fontsize=24)
    plt.tight_layout()
    # Create savedir
    if not os.path.exists(savedir):
        os.makedirs(savedir)
    plt.savefig(savedir + '/' + fname + ".png")
    plt.show()
    plt.close()
Пример #13
0
def takePicture():

    img = cv2.imread('output/20201024013736_ZWO_ASI294MC_Pro.tiff')
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    mean, median, std = sigma_clipped_stats(gray, sigma=3.0)
    print(f'mean:{mean} median:{median} std:{std}')
    daofind = DAOStarFinder(fwhm=5.0, threshold=5. * std)
    print(gray.shape, median.shape)
    sources = daofind(gray - median)
    for col in sources.colnames:
        sources[col].info.format = '%.8g'  # for consistent table output
    print(sources)

    import numpy as np
    import matplotlib.pyplot as plt
    from astropy.visualization import SqrtStretch
    from astropy.visualization.mpl_normalize import ImageNormalize
    from photutils import CircularAperture
    positions = np.transpose((sources['xcentroid'], sources['ycentroid']))
    apertures = CircularAperture(positions, r=4.)
    norm = ImageNormalize(stretch=SqrtStretch())
    plt.imshow(gray,
               cmap='Greys',
               origin='lower',
               norm=norm,
               interpolation='nearest')
    apertures.plot(color='blue', lw=1.5, alpha=0.5)
    plt.savefig('kk.png')
    cv2.namedWindow('Falcon')
    cv2.imshow('Falcon', gray)
    cv2.waitKey(0)

    return
Пример #14
0
def convert_to_valid_color(
    image_color: np.ndarray,
    clip: bool = False,
    lower_clip: float = 0.0,
    upper_clip: float = 1.0,
    normalize: bool = False,
    scaling: Optional[str] = None,
    simple_norm: bool = False,
) -> np.ndarray:
    """
    Convert the channel to a valid 0-1 range for RGB images
    """

    if simple_norm:
        interval = MinMaxInterval()
        norm = ImageNormalize()
        return norm(interval(image_color))

    if clip:
        image_color = np.clip(image_color, lower_clip, upper_clip)
    if normalize:
        interval = ManualInterval(lower_clip, upper_clip)
    else:
        interval = MinMaxInterval()
    if scaling == "sqrt":
        stretch = SqrtStretch()
        image_color = stretch(interval(image_color))
    else:
        norm = ImageNormalize()
        image_color = norm(interval(image_color))

    return image_color
Пример #15
0
def plot_peaks(box, x_peaks, y_peaks, radius=None, title=None, vmin=None, vmax=None):

    """
    This function plots the data with peaks marked ...
    :param box:
    :param x_peaks:
    :param y_peaks:
    :return:
    """

    # Determine the maximum value in the box and the minium value for plotting
    if vmin is None: vmin = max(np.nanmin(box), 0.)
    if vmax is None: vmax = 0.5 * (np.nanmax(box) + vmin)

    # Set the normalization
    norm = ImageNormalize(stretch=SqrtStretch())

    # Make the plot
    plt.figure(figsize=(8,2.5))
    plt.imshow(box, origin='lower', norm=norm, interpolation='nearest', vmin=vmin, vmax=vmax, cmap="viridis")

    if radius is None: plt.plot(x_peaks, y_peaks, ls='none', color='white', marker='+', ms=40, lw=10, mew=4)
    else:

        positions = (x_peaks, y_peaks)
        apertures = CircularAperture(positions, r=radius)
        apertures.plot(color='green', lw=1.5, alpha=0.5)

    plt.xlim(0, box.shape[1]-1)
    plt.ylim(0, box.shape[0]-1)

    if title is not None: plt.title(title)

    plt.show()
Пример #16
0
def plot_star(box, peak, model, title=None, vmin=None, vmax=None):

    """
    This function ...
    :param box:
    :param peak:
    :param model:
    :param title:
    :return:
    """

    # Normalization
    norm = ImageNormalize(stretch=SqrtStretch())

    # Determine the maximum value in the box and the minimum value for plotting
    if vmin is None: vmin = max(np.nanmin(box), 0.)
    if vmax is None: vmax = 0.5 * (np.nanmax(box) + vmin)

    # Evaluate the model and subtract it from the cutout
    evaluated = box.evaluate_model(model)
    subtracted = box - evaluated

    # Create a figure
    plt.figure(figsize=(10,3))

    # Plot the box
    plt.subplot(1,4,1)
    plt.imshow(box, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis")
    plt.plot(peak.x, peak.y, ls='none', color='white', marker='+', ms=40, lw=10, mew=4)
    plt.xlim(0, box.xsize-1)
    plt.ylim(0, box.ysize-1)
    plt.title("Cutout")

    # Plot the model
    plt.subplot(1,4,2)
    plt.imshow(evaluated, origin='lower', interpolation="nearest", norm=norm, vmin=0.0, vmax=vmax, cmap="viridis")
    plt.xlim(0, box.xsize-1)
    plt.ylim(0, box.ysize-1)
    plt.title("Model")

    # Plot the subtracted box on the same scale as the original box and model
    plt.subplot(1,4,3)
    plt.imshow(subtracted, origin='lower', interpolation="nearest", norm=norm, vmin=0.0, vmax=vmax, cmap="viridis")
    plt.xlim(0, box.xsize-1)
    plt.ylim(0, box.ysize-1)
    plt.title("Residual")

    # Plot the subtracted box on a narrower color scale
    plt.subplot(1,4,4)
    sp = plt.imshow(subtracted, origin='lower', interpolation="nearest", cmap="viridis")
    plt.xlim(0, box.xsize-1)
    plt.ylim(0, box.ysize-1)
    plt.title("Residual")
    plt.colorbar(sp, format="%.2f")

    # Set the main title
    if title is not None: plt.suptitle(title, size=16)

    # Show the plot
    plt.show()
Пример #17
0
def contour_plot(ax, contour_file, contour_type, image_beam):
    """Plots contours over the main image, can be either from the same image or from a different one, fits file."""

    cblock = import_contours(contour_file)
    cdata = cblock[0]
    cheader = cblock[1]
    cwcs = WCS(cheader)

    contour_type = str(contour_type)
    ax.set_autoscale_on(False)

    norm = ImageNormalize(cdata,
                          interval=MinMaxInterval(),
                          stretch=SqrtStretch())

    if contour_type == "automatic":
        spacing = contour_bias
        n = 6  #number of contours
        ub = np.max(cdata)
        lb = np.min(cdata)

        def level_func(lb, ub, n, spacing=1.1):
            span = (ub - lb)
            dx = 1.0 / (n - 1)
            return [lb + (i * dx)**spacing * span for i in range(n)]

        levels = level_func(lb, ub, n, spacing=float(spacing))
        levels = np.array(levels)[np.array(levels) > 0.]
        print('Generated Levels for contour are: ', levels, 'MJy/sr')
        CS = ax.contour(cdata,
                        levels=levels,
                        colors='black',
                        transform=ax.get_transform(cwcs.celestial),
                        alpha=1.0,
                        linewidths=1)
    if contour_type == "sigma":
        contour_levels = list(map(float, args.contour_levels))
        sigma_levels = np.array(contour_levels)
        rms = (0.0004 * u.Jy / u.beam).to(
            u.MJy / u.sr, equivalencies=u.beam_angular_area(image_beam))
        levels = rms * sigma_levels
        print('Sigma Levels for contour are: ', sigma_levels, 'sigma')
        CS = ax.contour(cdata,
                        levels=levels,
                        norm=norm,
                        transform=ax.get_transform(cwcs.celestial),
                        colors='white',
                        alpha=0.5)
        #plt.title(label='Contours at %s sigma' % contour_levels)
    if contour_type == "manual":
        levels = list(map(float, args.contour_levels))
        print('Contour Levels are: ', levels, 'MJy/sr')
        CS = ax.contour(cdata,
                        levels=levels,
                        norm=norm,
                        transform=ax.get_transform(cwcs.celestial),
                        colors='white',
                        alpha=0.5,
                        linewidths=1.0)
Пример #18
0
 def __init__(self):
     pass
     self.image_norms = {
         'log': LogStretch(),
         'linear': LinearStretch(),
         'sqrt': SqrtStretch(),
     }
     self.map = None
Пример #19
0
def plot_box(box, title=None, path=None, format=None, scale="log", interval="pts", cmap="viridis"):

    """
    This function ...
    :param box:
    :param title:
    :param path:
    :param format:
    :param scale:
    :param interval:
    :param cmap:
    :return:
    """

    # Other new colormaps: plasma, magma, inferno

    # Normalization
    if scale == "log": norm = ImageNormalize(stretch=LogStretch())
    elif scale == "sqrt": norm = ImageNormalize(stretch=SqrtStretch())
    #elif scale == "skimage": norm = exposure.equalize_hist
    else: raise ValueError("Invalid option for 'scale'")

    if interval == "zscale":

        vmin, vmax = ZScaleInterval().get_limits(box)

    elif interval == "pts":

        # Determine the maximum value in the box and the mimimum value for plotting
        vmin = max(np.nanmin(box), 0.)
        vmax = 0.5 * (np.nanmax(box) + vmin)

    elif interval == "minmax":

        vmin, vmax = MinMaxInterval().get_limits(box)

    elif isinstance(interval, tuple):

        vmin = interval[0]
        vmax = interval[1]

    else: raise ValueError("Invalid option for 'interval'")

    # Make the plot
    plt.figure(figsize=(7,7))
    plt.imshow(box, origin="lower", interpolation="nearest", vmin=vmin, vmax=vmax, norm=norm, cmap=cmap)
    plt.xlim(0, box.shape[1]-1)
    plt.ylim(0, box.shape[0]-1)

    if title is not None: plt.title(title)

    if path is None: plt.show()
    else: plt.savefig(path, format=format)

    plt.close()

    # Return vmin and vmax
    return vmin, vmax
Пример #20
0
def plotSatelliteTrail(imageArray, trailPoint1, trailPoint2, trailWidth):
    """Make three figures to illustrate the original and rotated image,
    summed flux profile of the satellite trail, and flux along the trail.

    Parameters
    ----------
    imageArray : np.array
        2D array containing image data.
    trailPoint1 : `list` with 2 values
        [x1, y1] coordinates of first point on trail, in pixels
    trailPoint2 : `list` with 2 values
        [x2, y2] coordinates of second point on trail, in pixels
    trailWidth : `int`
        Width of trail, in pixels
    """
    rotatedInfo = makeTrailHorizontal(imageArray, trailPoint1, trailPoint2,
                                      trailWidth)
    rotatedArray = rotatedInfo[0]
    trailRotX = rotatedInfo[1]
    trailRotY = rotatedInfo[2]
    sliced = rotatedInfo[3]
    trailLength = getTrailLength(trailPoint1, trailPoint2)
    norm = ImageNormalize(imageArray,
                          interval=ZScaleInterval(),
                          stretch=SqrtStretch())
    fig1 = plt.figure(figsize=(8, 4))
    fig1.add_subplot(121)
    plt.imshow(imageArray, cmap='gray', norm=norm, origin='lower')
    plt.plot([trailPoint1[0], trailPoint2[0]],
             [trailPoint1[1], trailPoint2[1]],
             ls=':',
             color='C0',
             lw=2)
    plt.title('Original image with satellite trail')
    fig1.add_subplot(122)
    plt.imshow(rotatedArray, cmap='gray', norm=norm, origin='lower')
    plt.axhline(y=trailRotY - trailWidth, ls=':', color='C1', lw=2)
    plt.axhline(y=trailRotY + trailWidth, ls=':', color='C1', lw=2)
    plt.axhline(y=trailRotY, ls=':', color='C0', lw=2)
    plt.plot(trailRotX, trailRotY, marker='o', color='C4')
    plt.plot(trailRotX + trailLength, trailRotY, marker='o', color='C4')
    plt.title('Rotated image with horizontal satellite trail')

    fig2 = plt.figure(figsize=(8, 4))
    ax2 = fig2.subplots()
    ax2.plot(sliced.sum(axis=1), marker='o')
    plt.xlabel('Pixel index')
    plt.ylabel('Flux (nJy)')
    plt.title('Summed flux profile')

    fig3 = plt.figure(figsize=(8, 4))
    ax3 = fig3.subplots()
    ax3.plot(sliced.sum(axis=0))
    plt.xlabel('Rotated X pixel position')
    plt.ylabel('Flux (nJy)')
    plt.title('Flux along the trail')
def background_reduction(List):

    Raw_Image_Data = []
    Reduced_Image_Data = []
    Bkg = []
    Bkg_Sigma = []
    Median = []
    Std = []
    Norm = ImageNormalize(stretch=SqrtStretch())

    for i in range(len(List)):

        Image_File = get_pkg_data_filename(f'RAW_DATA/{List[i]}')
        crmask, Raw_Image_Data_1 = astroscrappy.detect_cosmics(
            fits.getdata(Image_File, ext=0))
        Raw_Image_Data.append(Raw_Image_Data_1)

        Mask = (Raw_Image_Data_1 == 0)
        Sigma_Clip = SigmaClip(sigma=3.0)
        Bkg_Estimator = MedianBackground()

        Bkg_ta = Background2D(Raw_Image_Data_1, (25, 25),
                              filter_size=(3, 3),
                              sigma_clip=Sigma_Clip,
                              bkg_estimator=Bkg_Estimator,
                              mask=Mask)

        Bkg.append(Bkg_ta)

        Bkg_Sigma_ta = mad_std(Raw_Image_Data_1)
        Bkg_Sigma.append(Bkg_Sigma_ta)

        Mean, Median_ta, Std_ta = sigma_clipped_stats(Raw_Image_Data_1,
                                                      sigma=3.0)
        Median.append(Median_ta)
        Std.append(Std_ta)

        Reduced_Image_Data_to_append = Raw_Image_Data_1 - Bkg_ta.background
        Reduced_Image_Data.append(Reduced_Image_Data_to_append)

        #plt.figure()
        #plt.imshow(Raw_Image_Data_1, cmap = 'gray', origin = 'lower', interpolation = 'bicubic', norm = Norm, vmin = 100, vmax = 1000)
        #plt.colorbar()

        #plt.figure()
        #plt.imshow(Bkg_ta.background, origin='lower', cmap='gray', interpolation = 'bicubic')
        #plt.colorbar()

        #plt.figure()
        #plt.imshow(Reduced_Image_Data_to_append, norm = Norm, origin = 'lower', cmap = 'gray', interpolation = 'bicubic', vmin = 1, vmax = 1000)
        #plt.colorbar()

        #plt.show()

    return Raw_Image_Data, Reduced_Image_Data, Bkg, Bkg_Sigma, Median, Std
Пример #22
0
def find_sources(file_, fwhm):
    """
    Uses DAOStarFinder to extract source positions from fits file
    :param file_ (str): name of target .fits file
    :param fwhm (float): The full width half maximum of the gaussian kernel in pixels
    For more config see
    https://photutils.readthedocs.io/en/stable/api/photutils.detection.DAOStarFinder.html
    """
    # Read in fits file as numpy array
    data = read_fits(file_, return_array=True)
    # Calculate background level
    mean, median, std = stats.sigma_clipped_stats(data)
    print(('mean', 'median', 'std'))
    print((mean, median, std))
    # Set up DAO Finder and run on bg subtracted image, printing results
    # sharplo=.2, sharphi=1., roundlo=-.3, roundhi=.3,
    daofind = DAOStarFinder(exclude_border=True, fwhm=fwhm, threshold=std)
    sources = daofind.find_stars(data - median)  # daofind(data-median) #
    print('Sources:')
    print(sources)
    # Save positions of detected sources to csv file
    positions = (sources['xcentroid'], sources['ycentroid'])
    print_positions = zip(*[
        sources[x] for x in [
            'id', 'xcentroid', 'ycentroid', 'sharpness', 'roundness1',
            'roundness2', 'npix', 'sky', 'peak', 'flux', 'mag'
        ]
    ])
    header = 'id,xcentroid,ycentroid,sharpness,roundness1,roundness2,npix,sky,peak,flux,mag'
    np.savetxt(file_[:-5] + '_positions.csv',
               print_positions,
               fmt='%.5e',
               header=header)
    # Show image with detected sources circled in blue
    apertures = CircularAperture(positions, r=4.)
    norm = ImageNormalize(stretch=SqrtStretch())
    plt.imshow(data, cmap='Greys', origin='lower', norm=norm)
    apertures.plot(color='blue', lw=1.5, alpha=0.5)
    plt.draw()
    # Scatter plot sharpness vs magnitude
    plt.figure(2)
    sharp, round_, mags = (sources['sharpness'], sources['roundness1'],
                           sources['mag'])
    plt.scatter(mags, sharp)
    plt.title('Sharpness vs Magnitude')
    plt.xlabel('Mag')
    plt.ylabel('Sharp')
    # Scatter plot roundness vs magnitude
    plt.figure(3)
    plt.scatter(mags, round_)
    plt.title('Roundness vs Magnitude')
    plt.xlabel('Mag')
    plt.ylabel('Roundness1')
    plt.show()
Пример #23
0
def find_sources(data,
                 threshold=30,
                 fwhm=3.0,
                 show_sources=True,
                 save_sources=False,
                 plot_name='sources.png'):
    """Use photutils' DAOFind to locate sources in the input image.

    Parameters
    ----------
    data : numpy.ndarray
        2D image

    threshold : float
        Number of sigma above the background used to determine the
        presence of a source

    show_sources : bool
        If True, create an image with overlain marks showing sources

    save_sources : bool
        If True, save the image of the source locations at ```plot_name```

    plot_name : str
        Name of file to save the image with marked sources

    Returns
    -------
    sources : astropy.table.Table
        Table of source positions
    """
    mean, median, std = sigma_clipped_stats(data, sigma=3.0)
    daofind = DAOStarFinder(fwhm=fwhm, threshold=threshold * std)
    sources = daofind(data - median)
    if sources is not None:
        print('{} sources found.'.format(len(sources)))

        if show_sources or save_sources:
            positions = np.transpose(
                (sources['xcentroid'], sources['ycentroid']))
            apertures = CircularAperture(positions, r=4.)
            norm = ImageNormalize(stretch=SqrtStretch())
            plt.imshow(data, cmap='Greys', origin='lower', norm=norm)
            apertures.plot(color='blue', lw=1.5, alpha=0.5)
            if show_sources:
                plt.show()
            if save_sources:
                plt.savefig(plot_name)
                print('Plot saved to {}'.format(plot_name))
            plt.close()
    else:
        print('No sources found.')

    return sources
Пример #24
0
def display_trajectory(crop_coord, arrow_coord, axes, map, scale="logZscale"):
    image_file = get_pkg_data_filename(map)
    image_data = fits.getdata(image_file, ext=0)
    #    image_data = np.swapaxes(image_data,0,1)
    image_data = image_data[np.min([crop_coord[0], crop_coord[1]]
                                   ):np.max([crop_coord[0], crop_coord[1]]),
                            np.min([crop_coord[2], crop_coord[3]]):np.
                            max([crop_coord[2], crop_coord[3]])]
    real_arrow = [
        arrow_coord[0] - crop_coord[0], arrow_coord[1] - crop_coord[2],
        arrow_coord[2] - crop_coord[0] - (arrow_coord[0] - crop_coord[0]),
        -crop_coord[2] + arrow_coord[3] - (arrow_coord[1] - crop_coord[2])
    ]
    #print real_arrow
    ax = axes[1]
    if scale == "linZscale":
        norm = ImageNormalize(image_data,
                              interval=ZScaleInterval(contrast=0.1),
                              stretch=SqrtStretch())

        im = ax.imshow(image_data, cmap='gray', norm=norm)
        plt.colorbar(im, ax=ax)

    if scale == "logZscale":
        new_image_data = -2.5 * np.log10(abs(image_data))
        norm = ImageNormalize(new_image_data - np.min(new_image_data),
                              interval=ZScaleInterval(contrast=0.25),
                              stretch=SqrtStretch())
        im = ax.imshow(new_image_data - np.min(new_image_data),
                       aspect='auto',
                       cmap='gray')
        plt.colorbar(im, ax=ax)

    ax.arrow(real_arrow[1],
             real_arrow[0],
             real_arrow[3],
             real_arrow[2],
             head_width=50,
             head_length=50,
             fc='g',
             ec='g')
Пример #25
0
def starbright(fnstar, fnflat, istar, axs, fg):
    # %% load data
    data = meanstack(fnstar, 100)[0]
    # %% flat field
    flatnorm = readflat(fnflat, fnstar)
    data = (data / flatnorm).round().astype(data.dtype)
    # %% background
    mean, median, std = sigma_clipped_stats(data, sigma=3.0)

    rfact = data.shape[0] // 40
    cfact = data.shape[1] // 40
    bg = Background(data, (rfact, cfact), interp_order=1, sigclip_sigma=3)
    # http://docs.astropy.org/en/stable/units/#module-astropy.units
    # dataphot = (data - bg.background)*u.ph/(1e-4*u.m**2 * u.s * u.sr)
    #   data = (data-0.97*data.min()/bg.background.min()*bg.background) * u.ph/(u.cm**2 * u.s * u.sr)
    data = data * u.ph / (u.cm**2 * u.s * u.sr)
    # %% source extraction
    sources = daofind(data, fwhm=3.0, threshold=5 * std)
    # %% star identification and quantification
    XY = column_stack((sources["xcentroid"], sources["ycentroid"]))
    apertures = CircularAperture(XY, r=4.0)
    norm = ImageNormalize(stretch=SqrtStretch())

    flux = apertures.do_photometry(data, effective_gain=camgain)[0]
    # %% plots
    fg.suptitle("{}".format(fnflat.parent), fontsize="x-large")

    hi = axs[-3].imshow(flatnorm, interpolation="none", origin="lower")
    fg.colorbar(hi, ax=axs[-3])
    axs[-3].set_title("flatfield {}".format(fnflat.name))

    hi = axs[-2].imshow(bg.background, interpolation="none", origin="lower")
    fg.colorbar(hi, ax=axs[-2])
    axs[-2].set_title("background {}".format(fnstar.name))

    hi = axs[-1].imshow(data.value,
                        cmap="Greys",
                        origin="lower",
                        norm=norm,
                        interpolation="none")
    fg.colorbar(hi, ax=axs[-1])
    for i, xy in enumerate(XY):
        axs[-1].text(xy[0],
                     xy[1],
                     str(i),
                     ha="center",
                     va="center",
                     fontsize=16,
                     color="w")
    apertures.plot(ax=axs[-1], color="blue", lw=1.5, alpha=0.5)
    axs[-1].set_title("star {}".format(fnstar.name))

    return flux[istar]
Пример #26
0
def plot_removal(cutout, mask, background, removed, title=None, vmin=None, vmax=None):

    """
    This function ...
    :param cutout:
    :param mask:
    :param background:
    :param removed:
    :param title:
    :return:
    """

    # Get raw data of mask as a numpy array
    if hasattr(mask, "data"): maskdata = mask.data
    else: maskdata = mask

    norm = ImageNormalize(stretch=SqrtStretch())

    # Determine the maximum value in the box and the minimum value for plotting
    if vmin is None: vmin = max(np.nanmin(cutout), 0.)
    if vmax is None: vmax = 0.5 * (np.nanmax(cutout) + vmin)

    # Plot the data with the best-fit model
    plt.figure(figsize=(20,3))
    plt.subplot(1,4,1)
    plt.imshow(cutout, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis")
    plt.xlim(-0.5, cutout.xsize-0.5)
    plt.ylim(-0.5, cutout.ysize-0.5)
    plt.title("Cutout")

    plt.subplot(1,4,2)
    plt.imshow(np.ma.masked_array(cutout, mask=maskdata), origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis")
    plt.xlim(-0.5, cutout.xsize-0.5)
    plt.ylim(-0.5, cutout.ysize-0.5)
    plt.title("Background mask")

    plt.subplot(1,4,3)
    plt.imshow(background, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis")
    plt.xlim(-0.5, background.xsize-0.5)
    plt.ylim(-0.5, background.ysize-0.5)
    plt.title("Estimated background")

    plt.subplot(1,4,4)
    plt.imshow(removed, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis")
    plt.xlim(-0.5, background.xsize-0.5)
    plt.ylim(-0.5, background.ysize-0.5)
    plt.title("Cutout with star removed")

    # Set the main title
    if title is not None: plt.suptitle(title, size=16)

    # Show the plot
    plt.show()
Пример #27
0
    def __init__(self,
                 hdu,
                 plot=True,
                 num_std=20,
                 max_stars=300,
                 query_radius=5.):
        '''

        :param hdu:
        :param plot:
        :param num_std:
        :param max_stars:
        :param query_radius:
        '''

        self.data = hdu.data.copy()
        self.header = hdu.header.copy()

        # Extract star positions and magnitudes from image
        mean, med, std = sigma_clipped_stats(self.data)
        daofind = DAOStarFinder(fwhm=3, threshold=num_std * std)
        sources = daofind(self.data - med)
        self.pixel_positions = (sources['xcentroid'], sources['ycentroid'])
        self.inst_magnitudes = sources['mag']

        if (plot):
            apertures = CircularAperture(self.pixel_positions, r=4)
            norm = ImageNormalize(stretch=SqrtStretch())
            plt.imshow(self.data, cmap='Greys', origin='lower', norm=norm)
            apertures.plot(color='blue', lw=1.5, alpha=0.5)

        self.wcs_orig = wcs.WCS(self.header)
        (self.ra_orig,
         self.dec_orig) = self.wcs_orig.all_pix2world(self.pixel_positions[0],
                                                      self.pixel_positions[1],
                                                      0)
        arr_ref = query_vizier(query_radius,
                               self.header['CRVAL1'],
                               self.header['CRVAL2'],
                               max_stars=max_stars)
        self.ra_ref = arr_ref[:, 0]
        self.dec_ref = arr_ref[:, 1]
        self.mag_ref = arr_ref[:, 2]
        (self.xpix_ref,
         self.ypix_ref) = self.wcs_orig.all_world2pix(self.ra_ref,
                                                      self.dec_ref, 0)
        (self.xpix_orig, self.ypix_orig) = self.pixel_positions

        if (plot):

            ref_aper = CircularAperture((self.xpix_ref, self.ypix_ref), r=4)
            ref_aper.plot(color='red', lw=1.5, alpha=0.5)
            plt.show()
Пример #28
0
def find_sources_via_segmentation(data,
                                  sigma=3,
                                  fwhm=2.0,
                                  min_pix=5,
                                  make_plot=False):
    """
    """
    yd, xd = data.shape

    # Let's define the background using boxes of ~50x50 pixels
    nboxx = int(xd / 150)
    nboxy = int(yd / 150)
    bkg_estimator = MedianBackground()
    bkg = Background2D(data, (nboxy, nboxx),
                       filter_size=(3, 3),
                       bkg_estimator=bkg_estimator)

    data -= bkg.background  # subtract the background
    threshold = sigma * bkg.background_rms

    #threshold = detect_threshold(data, nsigma=sigma)

    gaussian_sigma = fwhm * gaussian_fwhm_to_sigma
    kernel = Gaussian2DKernel(gaussian_sigma, x_size=3, y_size=3)
    kernel.normalize(mode='integral')
    segm = detect_sources(data,
                          threshold,
                          npixels=min_pix,
                          filter_kernel=kernel)
    segm_deblend = deblend_sources(data,
                                   segm,
                                   npixels=min_pix,
                                   filter_kernel=kernel,
                                   nlevels=32,
                                   contrast=0.001)

    if make_plot:
        norm = ImageNormalize(stretch=SqrtStretch())
        fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 12.5))
        ax1.imshow(data, origin='lower', cmap='Greys_r', norm=norm)
        ax1.set_title('Data')
        cmap = segm.make_cmap(seed=123)
        ax2.imshow(segm, origin='lower', cmap=cmap, interpolation='nearest')
        ax2.set_title('Segmentation Image')
        ax3.imshow(segm_deblend,
                   origin='lower',
                   cmap=cmap,
                   interpolation='nearest')
        ax3.set_title('Deblended Segmentation Image')
        plt.show()
        #plt.save('testing.jpg')

    return data, segm_deblend, bkg
Пример #29
0
def convert_fits2png(fitsfile, png, scale="logZscale"):
    image_file = get_pkg_data_filename(fitsfile)
    image_data = fits.getdata(image_file, ext=0)
    #print real_arrow
    if scale == "linZscale":
        norm = ImageNormalize(image_data,
                              interval=ZScaleInterval(contrast=0.1),
                              stretch=SqrtStretch())

        im = plt.imshow(image_data, cmap='gray', norm=norm)

    if scale == "logZscale":
        new_image_data = -2.5 * np.log(abs(image_data))
        norm = ImageNormalize(new_image_data - np.min(new_image_data),
                              interval=ZScaleInterval(contrast=0.25),
                              stretch=SqrtStretch())
        im = plt.imshow(new_image_data - np.min(new_image_data),
                        aspect='auto',
                        cmap='gray')
    plt.show()
    im.savefig(png)
Пример #30
0
def plot_background_subtraction(background, background_clipped, est_background, star, est_background_star):

    """
    This function ...
    :param background:
    :param background_clipped:
    :param est_background:
    :param star:
    :param est_background_star:
    :param peaks:
    :return:
    """

    norm = ImageNormalize(stretch=SqrtStretch())

    # Determine the maximum value in the box and the minimum value for plotting
    vmax = np.nanmax(background)
    vmin = np.nanmin(background) if vmax <= 0 else 0.0

    # Plot the data with the best-fit model
    plt.figure(figsize=(20,3))
    plt.subplot(1,5,1)
    plt.imshow(background, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis")
    plt.xlim(0, background.shape[1]-1)
    plt.ylim(0, background.shape[0]-1)
    plt.title("Background")

    plt.subplot(1,5,2)
    plt.imshow(background_clipped, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis")
    plt.xlim(0, background_clipped.shape[1]-1)
    plt.ylim(0, background_clipped.shape[0]-1)
    plt.title("Sigma-clipped background")

    plt.subplot(1,5,3)
    plt.imshow(est_background, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis")
    plt.xlim(0, est_background.shape[1]-1)
    plt.ylim(0, est_background.shape[0]-1)
    plt.title("Estimated background")

    plt.subplot(1,5,4)
    plt.imshow(star, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis")
    plt.xlim(0, star.shape[1]-1)
    plt.ylim(0, star.shape[0]-1)
    plt.title("Star")

    plt.subplot(1,5,5)
    plt.imshow(star.data - est_background_star, origin='lower', interpolation="nearest", norm=norm, vmin=vmin, vmax=vmax, cmap="viridis")
    plt.xlim(0, star.shape[1]-1)
    plt.ylim(0, star.shape[0]-1)
    plt.title("Star without background")

    plt.show()