Exemple #1
0
def save_img(imgs, names, filename, min_size=(0, 0)):
    import f2n
    sys.path.append('./src/lib')
    nb = len(imgs)
    assert nb == len(names)
    l = int(round(np.sqrt(nb)))
    c = int(nb / l + (nb % l != 0.))
    size_max = min_size
    for im in imgs:
        x, y = im.shape
        size_max = ((x > size_max[0]) * x or size_max[0], (y > size_max[1]) * y
                    or size_max[1])
    im_list = []
    for i in xrange(nb):
        im = f2n.f2nimage(imgs[i], verbose=False)
        im.numpyarray = rebin(im.numpyarray,
                              size_max)  #TODO: use upsample instead
        im.setzscale(z2='ex')
        im.makepilimage()
        im.writetitle(names[i])
        im_list += [im]
    im_list = [[im_list[i + c * j] for i in xrange(c) if i + c * j < nb]
               for j in xrange(l)]
    for i in xrange(nb, c * l):
        fim = f2n.f2nimage(np.zeros(size_max), verbose=False)
        fim.makepilimage()
        im_list[-1] += [fim]
    f2n.compose(im_list, filename)
Exemple #2
0
	def make_plots(self,fprefix, basename):
                imag_path = os.path.join(fprefix, basename)
                z1=170
                z2=5000
                upsample = 1
                # The raw input array :
                im = f2n.f2nimage(self.getrawarray(), verbose=False)
                im.setzscale(z1, z2)
                im.makepilimage("log")
                im.upsample(upsample)
                im.writetitle("Input image", colour = (0,255,0))
                im.tonet(imag_path+"0_raw.png")
                
                
                # The mask of saturated stars, upon the raw image :
                im = f2n.f2nimage(self.getrawarray(), verbose=False)
                im.setzscale(z1, z2)
                im.makepilimage("log")
                im.drawmask(self.getsatstars(), colour=(255, 0, 255))
                im.upsample(upsample)
                im.writetitle("Saturated stars", colour = (0,255,0))
                im.tonet(imag_path+"1_satstars.png")
                   
                # We output a list of the positions of detected cosmic ray hits.
                # This is made on purpose to be fed into f2n's drawstarslist :
                labeldict = self.labelmask()
                im = f2n.f2nimage(self.getrawarray(), verbose=False)
                im.setzscale(z1, z2)
                im.makepilimage("log")
                im.drawmask(self.getsatstars(), colour=(255, 0, 255))
                im.upsample(upsample)
                im.drawstarslist(labeldict, colour=(255,0,0))
                im.writetitle("Cosmic ray hits", colour = (0,255,0))
                im.tonet(imag_path+"2_labels.png")
      
                # One png with the precise mask in green and a wider version in blue :
                im = f2n.f2nimage(self.getrawarray(), verbose=False)
                im.setzscale(z1, z2)
                im.makepilimage("log")
                im.drawmask(self.getdilatedmask(size=5), colour=(0, 0, 255))
                im.drawmask(self.getmask(), colour=(0, 255, 0))
                im.upsample(upsample)
                im.writetitle("Mask", colour = (0,255,0))
                im.tonet(imag_path+"3_mask.png")

                # And of course one png with the clean array :
                im = f2n.f2nimage(self.getcleanarray(), verbose=False)
                im.setzscale(z1, z2)
                im.makepilimage("log")
                im.upsample(upsample)
                im.writetitle("Cleaned image", colour = (0,255,0))
                im.tonet(imag_path+"4_clean.png")
Exemple #3
0
def affineremap(filepath, transform, shape, alifilepath=None,
                outdir="alipy_out", makepng=False, hdu=0, verbose=True):
    """
    Apply the simple affine transform to the image and saves the result as
    FITS, without using pyraf.

    :param filepath: FITS file to align
    :type filepath: string

    :param transform: as returned e.g. by alipy.ident()
    :type transform: SimpleTransform object

    :param shape: Output shape (width, height)
    :type shape: tuple

    :param alifilepath: where to save the aligned image. If None, I will put 
                        it in the outdir directory.
    :type alifilepath: string

    :param makepng: If True I make a png of the aligned image as well.
    :type makepng: boolean

    :param hdu: The hdu of the fits file that you want me to use. 0 is primary.
                If multihdu, 1 is usually science.
    """
    inv = transform.inverse()
    (matrix, offset) = inv.matrixform()
    # print matrix, offset

    data, hdr = fromfits(filepath, hdu=hdu, verbose=verbose)
    data = scipy.ndimage.interpolation.affine_transform(
        data, matrix, offset=offset, output_shape=shape)

    basename = os.path.splitext(os.path.basename(filepath))[0]

    if alifilepath == None:
        alifilepath = os.path.join(outdir, basename + "_affineremap.fits")
    else:
        outdir = os.path.split(alifilepath)[0]
    if not os.path.isdir(outdir):
        os.makedirs(outdir)

    tofits(alifilepath, data, hdr=None, verbose=verbose)

    if makepng:
        try:
            import f2n
        except ImportError:
            print("Couldn't import f2n -- install it !")
            return
        myimage = f2n.f2nimage(numpyarray=data, verbose=False)
        myimage.setzscale("auto", "auto")
        myimage.makepilimage("log", negative=False)
        myimage.writetitle(os.path.basename(alifilepath))
        if not os.path.isdir(outdir):
            os.makedirs(outdir)
        myimage.tonet(
            os.path.join(outdir, os.path.basename(alifilepath) + ".png"))
Exemple #4
0
def make_png(png_image_name, frame_name, data, rbin):
# requires f2n installed

    png_image = f2n.f2nimage(numpyarray=data)  # give the image data to f2n class
    png_image.setzscale("flat","flat")  # works best to my liking
    png_image.rebin(rbin)
    png_image.makepilimage("lin")       # linear image scaling.
    # we can play with marking the star and comparisons in the image, like so
    # png_image.drawcircle(112, 101, r=15) 
    # TBD later, for now just label the frame
    png_image.writetitle(frame_name, colour=(200, 200, 0))
    png_image.tonet(png_image_name)     # write the png.
Exemple #5
0
def affineremap(filepath,
                transform,
                shape,
                alifilepath=None,
                outdir="alipy_out",
                makepng=False,
                hdu=0,
                verbose=True,
                overwrite=False):
    """
    Apply the simple affine transform to the image and saves the result as
    FITS, without using pyraf.

    :param filepath: FITS file to align
    :type filepath: string

    :param transform: as returned e.g. by alipy.ident()
    :type transform: SimpleTransform object

    :param shape: Output shape (width, height)
    :type shape: tuple

    :param alifilepath: where to save the aligned image. If None, I will put
                        it in the outdir directory.
    :type alifilepath: string

    :param makepng: If True I make a png of the aligned image as well.
    :type makepng: boolean

    :param hdu: The hdu of the fits file that you want me to use. 0 is primary.
                If multihdu, 1 is usually science.
                
    :param overwrite: If True outdir is ignored and the original files will be overwrite.
    :type overwrite: boolean
    """
    inv = transform.inverse()
    (matrix, offset) = inv.matrixform()
    # print matrix, offset

    data, hdr = fromfits(filepath, hdu=hdu, verbose=verbose)
    data = scipy.ndimage.interpolation.affine_transform(data,
                                                        matrix,
                                                        offset=offset,
                                                        output_shape=shape)

    basename = os.path.splitext(os.path.basename(filepath))[0]

    if overwrite:
        alifilepath = filepath
        if alifilepath is None:
            alifilepath = os.path.join(outdir, basename + "_affineremap.fits")
        else:
            outdir = os.path.split(alifilepath)[0]
    if not os.path.isdir(outdir):
        os.makedirs(outdir)

    if hdr:
        tofits(alifilepath, data, hdr=hdr, verbose=verbose)
    else:
        tofits(alifilepath, data, hdr=None, verbose=verbose)

    if makepng:
        try:
            import f2n
        except ImportError:
            print("Couldn't import f2n -- install it !")
            return
        myimage = f2n.f2nimage(numpyarray=data, verbose=False)
        myimage.setzscale("auto", "auto")
        myimage.makepilimage("log", negative=False)
        myimage.writetitle(os.path.basename(alifilepath))
        if not os.path.isdir(outdir):
            os.makedirs(outdir)
        myimage.tonet(
            os.path.join(outdir,
                         os.path.basename(alifilepath) + ".png"))
Exemple #6
0
	f2ns.upsample(2)
	f2ns.writeinfo(["PSF"])
	"""

    # let's try to put the PSF in the right shape
    badpsf, h = fromfits(os.path.join(decdir, "s" + code + ".fits"),
                         verbose=False)
    goodpsf = np.zeros(badpsf.shape)
    psfsize = 128
    h = psfsize / 2
    goodpsf[:h, :h] = badpsf[h:, h:]
    goodpsf[:h, h:] = badpsf[h:, :h]
    goodpsf[h:, :h] = badpsf[:h, h:]
    goodpsf[h:, h:] = badpsf[:h, :h]

    f2ns = f2n.f2nimage(numpyarray=goodpsf, verbose=False)
    f2ns.setzscale(1.0e-8, "ex")
    f2ns.makepilimage(scale="log", negative=False)
    f2ns.upsample(2)
    f2ns.writeinfo(["PSF"])

    #legend = f2n.f2nimage(shape = (256,256), fill = 0.0, verbose=False)
    #legend.setzscale(0.0, 1.0)
    #legend.makepilimage(scale = "lin", negative = False)

    legend = f2n.f2nimage(shape=(64, 64), fill=0.0, verbose=False)
    legend.setzscale(0.0, 1.0)
    legend.makepilimage(scale="lin", negative=False)
    legend.upsample(4)
    for ptsrc in ptsrcs:
        print ptsrc.name
Exemple #7
0
def pngstampgrid(img,
                 cat,
                 pngfilepath,
                 xname="x",
                 yname="y",
                 stampsize=100,
                 ncols=5,
                 upsample=4,
                 z1="auto",
                 z2="auto"):
    """
	For this it uses the (slightly outdated) f2n.py module.

	:param img: either a galsim image or the filepath to a FITS image
	:param cat: an astropy table
	:param pngfilepath: the png file path to be written
	:param xname: colname for the x position (in pixel)
	:param yname: colname for y
	:param stampsize: stamp size (in pixels) to be extracted
	:param ncols: number of postage-stamp columns
	:param upsample: postage-stamp upsample rate
	:param z1: "z" scale low
	:param z2: "z" scale high
	
	"""

    if type(img) is str:
        logger.debug("Filepath given, loading the image...")
        img = tools.image.loadimg(img)

    n = len(cat)
    nrows = int(np.ceil(float(n) / float(ncols)))
    logger.info("Preparing %i x %i stamps of %i x %i pixels each..." %
                (ncols, nrows, stampsize, stampsize))

    stamprows = []
    for nrow in range(nrows):
        stamprow = []
        for ncol in range(ncols):

            index = ncol + ncols * nrow
            if index < n:  # Then we have a galaxy to show
                gal = cat[index]
                (x, y) = (gal[xname], gal[yname])
                (gps, flag) = tools.image.getstamp(x, y, img, stampsize)
                npstamp = gps.array

                f2nstamp = f2n.f2nimage(numpyarray=npstamp, verbose=False)

                f2nstamp.setzscale(z1, z2)
                f2nstamp.makepilimage("log", negative=False)
                f2nstamp.upsample(upsample)

                txt = [
                    "%i (%i, %i)" % (gal.index, x, y),
                ]
                f2nstamp.writeinfo(txt, colour=255)

                # Crosshair:
                s = stampsize
                f2nstamp.drawline(s / 2, s / 4, l=30, t=np.pi / 2.0)
                f2nstamp.drawline(s / 4, s / 2, l=30, t=0.0)

                # Just for reference, some other stuff from previous MomentsML versions:
                #f2nstamp.drawrectangle(1, s-1, 1, s-1)
                #f2nstamp.drawrectangle(140, s-140, 140, s-140, colour=(0,255,255))
                # Showing the measured shape, in red
                #e = np.hypot(galaxy.gal_e1, galaxy.gal_e2)
                #t = 0.5*np.arctan2(galaxy.gal_e2, galaxy.gal_e1)
                #f2nstamp.drawline(x = s/4, y=s/4 , l=150*e, t=t, width=3, colour=(255,0,0))

            else:  # No more galaxies, we just fill the splot with a grey empty stamp.
                npstamp = np.zeros((stampsize, stampsize))
                f2nstamp = f2n.f2nimage(numpyarray=npstamp, verbose=False)
                f2nstamp.setzscale(-1.0, 1.0)
                f2nstamp.makepilimage("lin", negative=False)
                f2nstamp.upsample(4)

            stamprow.append(f2nstamp)
        stamprows.append(stamprow)
    f2n.compose(stamprows, pngfilepath)
    logger.info("Wrote %s" % (pngfilepath))
Exemple #8
0
reportpath = os.path.join(workdir, "report_" + psfkey)
report = open(reportpath, 'w')

for i, image in enumerate(images):

    print "- " * 30
    print i + 1, image['imgname']
    toreport = str(image['imgname']) + '\t' + str(i + 1)
    report.write(toreport)

    imgpsfdir = os.path.join(psfdir, image['imgname'])
    resultsdir = os.path.join(imgpsfdir, "results")

    pngpath = os.path.join(pngdir, image['imgname'] + ".png")

    blank256 = f2n.f2nimage(shape=(256, 256), fill=0.0, verbose=False)
    blank256.setzscale(0.0, 1.0)
    blank256.makepilimage(scale="lin", negative=False)

    totpsfimg = f2n.fromfits(os.path.join(resultsdir, "psf_1.fits"),
                             verbose=False)
    #totpsfimg.rebin(2)
    totpsfimg.setzscale(1.0e-7, 1.0e-3)
    totpsfimg.makepilimage(scale="log", negative=False)
    totpsfimg.upsample(2)
    totpsfimg.writetitle("Total PSF")

    numpsfimg = f2n.fromfits(os.path.join(resultsdir, "psf_num_1.fits"),
                             verbose=False)
    numpsfimg.setzscale(-0.02, 0.02)
    numpsfimg.makepilimage(scale="lin", negative=False)