def make_RGB(sigmax=3,sigmin=1,write=False):
    
    Blue,header = fits.getdata('Blue.fit',0,header=True)
    Green,header = fits.getdata('Green.fit',0,header=True)    
    Red,header = fits.getdata('Red.fit',0,header=True)
    
    bmed = np.median(Blue)
    gmed = np.median(Green)
    rmed = np.median(Red)
    
    bsig = rb.std(Blue)
    gsig = rb.std(Green)                
    rsig = rb.std(Red)
        
    final = np.zeros((Blue.shape[0],Blue.shape[1],3),dtype=float)
    
    final[:,:,0] = img_scale.sqrt(Red,scale_min=rmed+sigmin*rsig,scale_max=rmed+sigmax*rsig)
    final[:,:,1] = img_scale.sqrt(Green,scale_min=gmed+sigmin*gsig,scale_max=gmed+sigmax*gsig)
    final[:,:,2] = img_scale.sqrt(Blue,scale_min=bmed+sigmin*bsig,scale_max=bmed+sigmax*bsig)

    plt.ion()
    plt.figure(99)
    plt.imshow(final,aspect='equal')

    if write:
        plt.savefig('RGB.png',dpi=300)
    
    return
Beispiel #2
0
def fits_to_jpg(rfile, gfile, bfile, name):
    r = fits.getdata(rfile)
    b = fits.getdata(bfile)
    g = fits.getdata(gfile)
    img = np.zeros((r.shape[0], r.shape[1], 3), dtype=float)

    img[:, :, 0] = img_scale.sqrt(r, scale_min=r.min(), scale_max=r.max() + 50)
    img[:, :, 1] = img_scale.sqrt(g, scale_min=g.min(), scale_max=g.max() + 50)
    img[:, :, 2] = img_scale.sqrt(b, scale_min=b.min(), scale_max=b.max() + 50)

    import matplotlib.pyplot as plt
    plt.imshow(img, aspect='equal')
    plt.savefig(str(name) + '.jpg')
Beispiel #3
0
def make_RGB():

    Blue,header = pf.getdata('Blue.fit',0,header=True)
    Green,header = pf.getdata('Green.fit',0,header=True)
    Red,header = pf.getdata('Red.fit',0,header=True)

    G = h.pyfits.open('Green.fit')
    Gh = h.pyfits.getheader('Green.fit')
    
    B = h.pyfits.open('Blue.fit')
    Bh = h.pyfits.getheader('Blue.fit')
    
    R = h.pyfits.open('Red.fit')
    Rh = h.pyfits.getheader('Red.fit')

    Bnew = h.hcongrid(B[0].data,B[0].header,Gh)
    Rnew = h.hcongrid(R[0].data,R[0].header,Gh)
    
    Blue = Bnew
    Green,header = readimage('Green.fit')
    Red = Rnew

    bmed = np.median(Blue)
    gmed = np.median(Green)
    rmed = np.median(Red)
    
    bsig = rb.std(Blue)
    gsig = rb.std(Green)
    rsig = rb.std(Red)
    
    final = np.zeros((Blue.shape[0],Blue.shape[1],3),dtype=float)  
    
    sigmin = 1.25
    sigmax = 15
    
    final[:,:,0] = img_scale.sqrt(Red,scale_min=rmed+sigmin*rsig,scale_max=rmed+0.6*sigmax*rsig)
    final[:,:,1] = img_scale.sqrt(Green,scale_min=gmed+sigmin*gsig,scale_max=gmed+0.6*sigmax*gsig)
    final[:,:,2] = img_scale.sqrt(Blue,scale_min=bmed+sigmin*bsig,scale_max=bmed+0.6*sigmax*bsig)
    
    plt.ion()
    plt.figure(99)
    #plt.imshow(img,aspect='equal')
    plt.xlim(250,1550)
    plt.ylim(288,1588)
    plt.xticks([])
    plt.yticks([])
    plt.imshow(final,aspect='equal')

    return
Beispiel #4
0
def composite(map_r,map_g,map_b,rotate=0.0,filename='none'):
    
    img=np.zeros((map_r.get('Inu').shape[0],map_r.get('Inu').shape[1],3))

    img[:,:,0] = img_scale.sqrt(map_r.get('Inu'))
    img[:,:,1] = img_scale.sqrt(map_g.get('Inu'))
    img[:,:,2] = img_scale.sqrt(map_b.get('Inu'))

    img = scipy.ndimage.rotate(img, rotate, reshape=False,order=1) 

    fig=plt.figure(frameon=False)
    plt.imshow(img, aspect='equal',origin='lower')
    ax=fig.add_subplot(1,1,1)
    ax.set_axis_off()
    ax.set_aspect('equal')
    
    if filename == 'none':
        plt.show()
    else: 
        fig.set_size_inches(4,4)
        extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
        plt.savefig(filename,bbox_inches=extent)
        plt.close()
Beispiel #5
0
def composite(map_r,map_g,map_b,rotate=0.0,filename='none'):
    
    img=np.zeros((map_r.get('Inu').shape[0],map_r.get('Inu').shape[1],3))

    img[:,:,0] = img_scale.sqrt(map_r.get('Inu'))
    img[:,:,1] = img_scale.sqrt(map_g.get('Inu'))
    img[:,:,2] = img_scale.sqrt(map_b.get('Inu'))

    img = scipy.ndimage.rotate(img, rotate, reshape=False,order=1) 

    fig=plt.figure(frameon=False)
    plt.imshow(img, aspect='equal',origin='lower')
    ax=fig.add_subplot(1,1,1)
    ax.set_axis_off()
    ax.set_aspect('equal')
    
    if filename == 'none':
        plt.show()
    else: 
        fig.set_size_inches(4,4)
        extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
        plt.savefig(filename,bbox_inches=extent)
        plt.close()
Beispiel #6
0
def getimg(inimg, noise, pc, cut, smooth):
    if smooth:
        inimg = ndimage.gaussian_filter(inimg, smooth)
    if cut != []:
        inimg = inimg[cut[0]:cut[1], cut[0]:cut[1]]
    inimg[:, 0] = inimg[:, -1] = inimg[0, :] = inimg[-1, :] = inimg.max()
    isiz = inimg.shape[0]
    b = np.sort(np.ravel(inimg[isiz / 3:2 * isiz / 3, isiz / 3:2 * isiz / 3]))
    black = b[min(pc * len(b) / 100, len(b) - 1)]
    black = max(black, noise)
    inimg = img_scale.sqrt(inimg, scale_min=0, scale_max=black)
    if RGB:
        inimg /= inimg.max()
    return inimg
Beispiel #7
0
 def doScaling(self, img, rgb):
     for j in range(3):
         smin, it = img_scale.sky_mean_sig_clip(rgb[j], self.SKY_SIGMA,
                                                self.SKY_CONVERGENCE)
         pxmax = max(rgb[j].flatten())
         smax = int(self.wb[j] *
                    (self.SCALE_RANGE / self.opt['scaling'] + smin))
         #            smax = int((self.SCALE_RANGE + smin) / self.wb[j])
         if self.SCALE_METHOD == self.scaleMethods[0]:
             img[:, :, j] = img_scale.linear(rgb[j],
                                             scale_min=smin,
                                             scale_max=smax)
         elif self.SCALE_METHOD == self.scaleMethods[1]:
             img[:, :, j] = img_scale.sqrt(rgb[j],
                                           scale_min=smin,
                                           scale_max=smax)
         elif self.SCALE_METHOD == self.scaleMethods[2]:
             img[:, :, j] = img_scale.log(rgb[j],
                                          scale_min=smin,
                                          scale_max=smax)
         elif self.SCALE_METHOD == self.scaleMethods[3]:
             img[:, :, j] = img_scale.asinh(rgb[j],
                                            scale_min=smin,
                                            scale_max=smax)
Beispiel #8
0
im_h = fits.getheader(im_file1)
im_w = wcs.WCS(im_h)
im_coo = np.round(im_w.wcs_world2pix(im_coo_wcs, 1))
im_size = np.array([im_coo[1, 0] - im_coo[0, 0], im_coo[1, 1] - im_coo[0, 1]],
                   np.int_)
r = r[im_coo[0, 0]:im_coo[0, 0] + im_size[0],
      im_coo[0, 1]:im_coo[0, 1] + im_size[1]]

im_h = fits.getheader(im_file2)
im_w = wcs.WCS(im_h)
im_coo = np.round(im_w.wcs_world2pix(im_coo_wcs, 1))
g = g[im_coo[0, 0]:im_coo[0, 0] + im_size[0],
      im_coo[0, 1]:im_coo[0, 1] + im_size[1]]

im_h = fits.getheader(im_file3)
im_w = wcs.WCS(im_h)
im_coo = np.round(im_w.wcs_world2pix(im_coo_wcs, 1))
b = b[im_coo[0, 0]:im_coo[0, 0] + im_size[0],
      im_coo[0, 1]:im_coo[0, 1] + im_size[1]]

img = np.zeros((r.shape[0], r.shape[1], 3), dtype=float)
img[:, :, 0] = img_scale.sqrt(r, scale_min=-15, scale_max=60)
img[:, :, 1] = img_scale.sqrt(g, scale_min=-3, scale_max=15)
img[:, :, 2] = img_scale.sqrt(b, scale_min=-2, scale_max=10)

py.clf()
py.imshow(img, aspect='equal')
py.title('Blue = u, Green = g, Red = i')
py.savefig('fornax_tile1_ugi.png')
hdulist = fits.open(fn)
img_header = hdulist[0].header
img_data_raw = hdulist[0].data
hdulist.close()
width=img_data_raw.shape[0]
height=img_data_raw.shape[1]
print("#INFO : ", fn, width, height)
img_data_raw = numpy.array(img_data_raw, dtype=float)
#sky, num_iter = img_scale.sky_median_sig_clip(img_data, sig_fract, percent_fract, max_iter=100)
sky, num_iter = img_scale.sky_mean_sig_clip(img_data_raw, sig_fract, percent_fract, max_iter=10)
print("sky = ", sky, '(', num_iter, ')')
img_data = img_data_raw - sky
min_val = 0.
print("... min. and max. value : ", numpy.min(img_data), numpy.max(img_data))

new_img = img_scale.sqrt(img_data, scale_min = min_val)
pylab.imshow(new_img, interpolation='nearest', origin='lower', cmap=pylab.cm.hot)
pylab.axis('off')
pylab.savefig('sqrt.png')
pylab.clf()
new_img = img_scale.power(img_data, power_index=3.0, scale_min = min_val)
pylab.imshow(new_img, interpolation='nearest', origin='lower', cmap=pylab.cm.hot)
pylab.axis('off')
pylab.savefig('power.png')
pylab.clf()
new_img = img_scale.log(img_data, scale_min = min_val)
pylab.imshow(new_img, interpolation='nearest', origin='lower', cmap=pylab.cm.hot)
pylab.axis('off')
pylab.savefig('log.png')
pylab.clf()
new_img = img_scale.linear(img_data, scale_min = min_val)
Beispiel #10
0
import os
import numpy as np
from PIL import Image
from astropy.io import fits
import img_scale
#from astropy.utils.data import download_file
#image_file = download_file('http://data.astropy.org/tutorials/FITS-images/HorseHead.fits', cache=True )

dir_path = os.getcwd()
for filename in os.listdir(dir_path + "\\data"):
    if filename.endswith(".fits"):
        image_data = fits.getdata("data\\" + filename)
        if len(image_data.shape) == 2:
            sum_image = image_data
        else:
            sum_image = image_data[0] - image_data[0]
            for single_image_data in image_data:
                sum_image += single_image_data

        sum_image = img_scale.sqrt(sum_image,
                                   scale_min=0,
                                   scale_max=np.amax(image_data))
        sum_image = sum_image * 200
        im = Image.fromarray(sum_image)
        if im.mode != 'RGB':
            im = im.convert('RGB')

        im.save(dir_path + "\\image\\" + filename + ".jpg")
        im.close()
hdulist = pyfits.open(fn)
img_header = hdulist[0].header
img_data_raw = hdulist[0].data
hdulist.close()
width = img_data_raw.shape[0]
height = img_data_raw.shape[1]
print "#INFO : ", fn, width, height
img_data_raw = numpy.array(img_data_raw, dtype=float)
# sky, num_iter = img_scale.sky_median_sig_clip(img_data, sig_fract, percent_fract, max_iter=100)
sky, num_iter = img_scale.sky_mean_sig_clip(img_data_raw, sig_fract, percent_fract, max_iter=10)
print "sky = ", sky, "(", num_iter, ")"
img_data = img_data_raw - sky
min_val = 0.0
print "... min. and max. value : ", numpy.min(img_data), numpy.max(img_data)

new_img = img_scale.sqrt(img_data, scale_min=min_val)
pylab.imshow(new_img, interpolation="nearest", origin="lower", cmap=pylab.cm.hot)
pylab.axis("off")
pylab.savefig("sqrt.png")
pylab.clf()
new_img = img_scale.power(img_data, power_index=3.0, scale_min=min_val)
pylab.imshow(new_img, interpolation="nearest", origin="lower", cmap=pylab.cm.hot)
pylab.axis("off")
pylab.savefig("power.png")
pylab.clf()
new_img = img_scale.log(img_data, scale_min=min_val)
pylab.imshow(new_img, interpolation="nearest", origin="lower", cmap=pylab.cm.hot)
pylab.axis("off")
pylab.savefig("log.png")
pylab.clf()
new_img = img_scale.linear(img_data, scale_min=min_val)
Beispiel #12
0
            dec_target = float(dec_target)
            cd=math.cos(dec_target*3.14159/180.) 
            ax["fk5"].plot([ra_target+6*arcmin, ra_target+10*arcmin], [dec_target, dec_target], "r")
            ax["fk5"].plot([ra_target-6*arcmin, ra_target-10*arcmin], [dec_target, dec_target], "r")
            ax["fk5"].plot([ra_target, ra_target], [dec_target+6*arcmin*cd, dec_target+10*arcmin*cd], "r")
            ax["fk5"].plot([ra_target, ra_target], [dec_target-6*arcmin*cd, dec_target-10*arcmin*cd], "r")
            
            # annotate the target
            from matplotlib.patheffects import withStroke
            myeffect = withStroke(foreground="w", linewidth=0)
            kwargs = dict(path_effects=[myeffect])
            ax["fk5"].annotate((target.replace("_"," ")), (ra_target-13*arcmin,dec_target), size=8, ha="left", va="center", **kwargs)
            
            # draw the image
            (sky,niter) = img_scale.sky_median_sig_clip(data,0.01,0.1,10)
            scaled_data = img_scale.sqrt(data,scale_min=sky-300,scale_max=sky+10000)
            ax[h_original].imshow_affine(scaled_data, origin='lower', cmap=plt.cm.gray_r)
            ax.grid()
            grayscale_drawn = True


        # Outline the frame limits. This gets done for all frames.
        i_a, j_a = (0.0 + 1.0), (0.0 + 1.0)
        [ra_a, dec_a], = w_original.wcs_pix2world([[i_a, j_a]], 1)

        i_b, j_b = (float(nx) + 1.0), (0 + 1.0)
        [ra_b, dec_b], = w_original.wcs_pix2world([[i_b, j_b]], 1)

        i_c, j_c = (float(nx) + 1.0), (float(ny) + 1.0)
        [ra_c, dec_c], = w_original.wcs_pix2world([[i_c, j_c]], 1)
Beispiel #13
0
r = pyfits.getdata(im_file1)
g = pyfits.getdata(im_file2)
b = pyfits.getdata(im_file3)

im_h = fits.getheader(im_file1)
im_w = wcs.WCS(im_h)
im_coo = np.round(im_w.wcs_world2pix(im_coo_wcs, 1))
im_size=np.array([im_coo[1,0]-im_coo[0,0],im_coo[1,1]-im_coo[0,1]], np.int_)
r = r[im_coo[0,0]:im_coo[0,0]+im_size[0], im_coo[0,1]:im_coo[0,1]+im_size[1]]

im_h = fits.getheader(im_file2)
im_w = wcs.WCS(im_h)
im_coo = np.round(im_w.wcs_world2pix(im_coo_wcs, 1))
g = g[im_coo[0,0]:im_coo[0,0]+im_size[0], im_coo[0,1]:im_coo[0,1]+im_size[1]]

im_h = fits.getheader(im_file3)
im_w = wcs.WCS(im_h)
im_coo = np.round(im_w.wcs_world2pix(im_coo_wcs, 1))
b = b[im_coo[0,0]:im_coo[0,0]+im_size[0], im_coo[0,1]:im_coo[0,1]+im_size[1]]

img = np.zeros((r.shape[0], r.shape[1], 3), dtype=float)
img[:,:,0] = img_scale.sqrt(r, scale_min=-15, scale_max=60)
img[:,:,1] = img_scale.sqrt(g, scale_min=-3, scale_max=15)
img[:,:,2] = img_scale.sqrt(b, scale_min=-2, scale_max=10)

py.clf()
py.imshow(img, aspect='equal')
py.title('Blue = u, Green = g, Red = i')
py.savefig('fornax_tile1_ugi.png')
        j = int(j)
        print "target is at (%d,%d)" % (i,j)
        if (i<100 or j<100 or i>(nx-100) or j>(nx-100)):
            raise StampError()
        data = data[i-100:i+100,j-100:j+100]
        
    except KeyError:
        print "Image %s does not contain a WCS" % this_image
        data = data[1576:1776,1166:1366]
        
    except StampError:
        print "Image %s does not contain the target. The center of the image is being used instead." % this_image
        data = data[1576:1776,1166:1366]       
    
    (sky,niter) = img_scale.sky_median_sig_clip(data,0.01,0.1,10)
    small_images.append(img_scale.sqrt(data,scale_min=sky-100,scale_max=sky+5000))


# Define the canvas properties
fig = py.figure(figsize=(15,7.5))
fig.subplots_adjust(hspace = 0.15, wspace = 0, top=0.95, bottom=0.01, left=0.0,
        right=1.0)

# Render mosaic 
for index in range(len(files)):
    a = fig.add_subplot(2,5,camera_subplot_index(files[index]))
    py.axis('off')
    py.imshow(small_images[index],aspect='equal',cmap = cm.Greys)
    py.title(os.path.basename(files[index]))

# Save as a single image
Beispiel #15
0
    def run(self):
        """ Runs the combining algorithm. The self.datain is run
            through the code, the result is in self.dataout.
        """
        ''' Select 3 input dataset to use, store in datause '''
        #Store number of inputs
        num_inputs = len(self.datain)
        # Create variable to hold input files
        # Copy input to output header and filename
        datause = []
        self.log.debug('Number of input files = %d' % num_inputs)

        # Ensure datause has 3 elements irrespective of number of input files
        if num_inputs == 0:  # Raise exception for no input
            raise ValueError('No input')
        elif num_inputs == 1:
            datause = [self.datain[0], self.datain[0], self.datain[0]]
        elif num_inputs == 2:
            datause = [self.datain[0], self.datain[1], self.datain[1]]
#elif num_inputs == 3:
#    datause = [self.datain[0], self.datain[1], self.datain[2]]
        else:  # If inputs exceed 3 in number
            ilist = []  # Make empty lists for each filter
            rlist = []
            glist = []
            other = []
            for element in self.datain:  # Loop through the input files and add to the lists
                fname = element.filename.lower()
                if 'i-band' in fname or 'iband' in fname or 'iprime' in fname:
                    ilist.append(element)
                elif 'r-band' in fname or 'rband' in fname or 'rprime' in fname:
                    rlist.append(element)
                elif 'g-band' in fname or 'gband' in fname or 'gprime' in fname:
                    glist.append(element)
                else:
                    other.append(element)
                    continue
            self.log.debug(
                'len(ilist) = %d, len(rlist) = %d, len(glist) = %d' %
                (len(ilist), len(rlist), len(glist)))
            # If there is at least one i-, r-, and g-band filter found in self.datain (best case)
            if len(ilist) >= 1 and len(rlist) >= 1 and len(glist) >= 1:
                # The first image from each filter list will be reduced in the correct order.
                datause = [ilist[0], rlist[0], glist[0]]
            elif len(ilist) == 0 and len(rlist) >= 1 and len(glist) >= 1:
                # Cases where there is no ilist
                if len(rlist) > len(glist):
                    datause = [rlist[0], rlist[1], glist[0]]
                else:
                    datause = [rlist[0], glist[0], glist[1]]
            elif len(glist) == 0 and len(rlist) >= 1 and len(ilist) >= 1:
                # Cases where there is no glist
                if len(rlist) > len(ilist):
                    datause = [rlist[0], rlist[1], ilist[0]]
                else:
                    datause = [rlist[0], ilist[0], ilist[1]]
            elif len(ilist) == 0 and len(rlist) >= 1 and len(glist) >= 1:
                # Cases where there is no rlist
                if len(ilist) > len(glist):
                    datause = [ilist[0], ilist[1], glist[0]]
                else:
                    datause = [ilist[0], glist[0], glist[1]]
            elif len(rlist) == 0 and len(glist) == 0:
                # Case where there is only ilist
                datause = [ilist[0], ilist[1], ilist[2]]
            elif len(rlist) == 0 and len(ilist) == 0:
                # Case where there is only glist
                datause = [glist[0], glist[1], glist[2]]
            elif len(ilist) == 0 and len(glist) == 0:
                # Case where there is only rlist
                datause = [rlist[0], rlist[1], rlist[2]]
        self.log.debug(
            'Files used: R = %s  G = %s  B = %s' %
            (datause[0].filename, datause[1].filename, datause[2].filename))
        self.dataout = PipeData(config=self.config)
        self.dataout.header = datause[0].header
        self.dataout.filename = datause[0].filename
        img = datause[0].image
        img1 = datause[1].image
        img2 = datause[2].image
        ''' Finding Min/Max scaling values '''
        # Create a Data Cube with floats
        datacube = numpy.zeros((img.shape[0], img.shape[1], 3), dtype=float)
        # Enter the image data into the cube so an absolute max can be found
        datacube[:, :, 0] = img
        datacube[:, :, 1] = img1
        datacube[:, :, 2] = img2
        # Find how many data points are in the data cube
        datalength = img.shape[0] * img.shape[1] * 3
        # Create a 1-dimensional array with all the data, then sort it
        datacube.shape = (datalength, )
        datacube.sort()
        # Now use arrays for each filter to find separate min values
        rarray = img.copy()
        garray = img1.copy()
        barray = img2.copy()
        # Shape and sort the arrays
        arrlength = img.shape[0] * img.shape[1]
        rarray.shape = (arrlength, )
        rarray.sort()
        garray.shape = (arrlength, )
        garray.sort()
        barray.shape = (arrlength, )
        barray.sort()
        # Find the min/max percentile values in the data for scaling
        # Values are determined by parameters in the pipe configuration file
        minpercent = int(arrlength * self.getarg('minpercent'))
        maxpercent = int(datalength * self.getarg('maxpercent'))
        # Find the final data values to use for scaling from the image data
        rminsv = rarray[minpercent]  #sv stands for "scalevalue"
        gminsv = garray[minpercent]
        bminsv = barray[minpercent]
        maxsv = datacube[maxpercent]
        self.log.info(' Scale min r/g/b: %f/%f/%f' % (rminsv, gminsv, bminsv))
        self.log.info(' Scale max: %f' % maxsv)
        # The same min/max values will be used to scale all filters
        ''' Finished Finding scaling values	'''
        ''' Combining Function '''
        # Make new cube with the proper data type for color images (uint8)
        # Use square root (sqrt) scaling for each filter
        # log or asinh scaling is also available
        imgcube = numpy.zeros((img.shape[0], img.shape[1], 3), dtype='uint8')
        imgcube[:, :, 0] = 255 * img_scale.sqrt(
            datause[0].image, scale_min=rminsv, scale_max=maxsv)
        imgcube[:, :, 1] = 255 * img_scale.sqrt(
            datause[1].image, scale_min=gminsv, scale_max=maxsv)
        imgcube[:, :, 2] = 255 * img_scale.sqrt(
            datause[2].image, scale_min=bminsv, scale_max=maxsv)
        self.dataout.image = imgcube
        # Create variable containing all the scaled image data
        imgcolor = Image.fromarray(self.dataout.image, mode='RGB')
        # Save colored image as a .tif file (without the labels)
        imgcolortif = imgcube.copy()
        imgcolortif.astype('uint16')
        ### tiff.imsave('%s.tif' % self.dataout.filenamebase, imgcolortif)
        ''' End of combining function '''
        ''' Add a Label to the Image '''
        draw = ImageDraw.Draw(imgcolor)
        # Use a variable to make the positions and size of text relative
        imgwidth = img.shape[1]
        imgheight = img.shape[0]
        # Open Sans-Serif Font with a size relative to the picture size
        try:
            # This should work on Linux
            font = ImageFont.truetype(
                '/usr/share/fonts/liberation/LiberationSans-Regular.ttf',
                imgheight / 41)
        except:
            try:
                # This should work on Mac
                font = ImageFont.truetype('/Library/Fonts/arial.ttf',
                                          imgheight / 41)
            except:
                # This should work on Windows
                font = ImageFont.truetype(r'C:\Windows\Fonts\arial.tff',
                                          imgheight / 41)
                # If this still doesn't work - then add more code to make it run on YOUR system
# Use the beginning of the FITS filename as the object name
        filename = os.path.split(self.dataout.filename)[-1]
        objectname = filename.split('_')[0]
        objectname = objectname[0].upper() + objectname[1:]
        objectname = 'Object:  %s' % objectname
        # Read labels at their respective position (kept relative to image size)
        # Left corner: object, observer, observatory
        # Right corner: Filters used for red, green, and blue colors
        draw.text((imgwidth / 100, imgheight / 1.114),
                  objectname, (255, 255, 255),
                  font=font)
        # Read FITS keywords for the observer, observatory, and filters
        if 'OBSERVER' in self.dataout.header:
            observer = 'Observer:  %s' % self.dataout.getheadval('OBSERVER')
            draw.text((imgwidth / 100, imgheight / 1.073),
                      observer, (255, 255, 255),
                      font=font)
        if 'OBSERVAT' in self.dataout.header:
            observatory = 'Observatory:  %s' % self.dataout.getheadval(
                'OBSERVAT')
            draw.text((imgwidth / 100, imgheight / 1.035),
                      observatory, (255, 255, 255),
                      font=font)
        if 'FILTER' in datause[0].header:
            red = 'R:  %s' % datause[0].getheadval('FILTER')
            draw.text((imgwidth / 1.15, imgheight / 1.114),
                      red, (255, 255, 255),
                      font=font)
        if 'FILTER' in datause[1].header:
            green = 'G:  %s' % datause[1].getheadval('FILTER')
            draw.text((imgwidth / 1.15, imgheight / 1.073),
                      green, (255, 255, 255),
                      font=font)
        if 'FILTER' in datause[2].header:
            blue = 'B:  %s' % datause[2].getheadval('FILTER')
            draw.text((imgwidth / 1.15, imgheight / 1.035),
                      blue, (255, 255, 255),
                      font=font)

# Save the completed image
        imgcolor.save('%sjpg' % self.dataout.filenamebegin)
        self.log.info('Saving file %sjpg' % self.dataout.filenamebegin)
        ''' End of Label Code '''
        # Set complete flag
        self.dataout.setheadval('COMPLETE', 1,
                                'Data Reduction Pipe: Complete Data Flag')
Beispiel #16
0
        print "target is at (%d,%d)" % (i, j)
        if (i < 100 or j < 100 or i > (nx - 100) or j > (nx - 100)):
            raise StampError()
        data = data[i - 100:i + 100, j - 100:j + 100]

    except KeyError:
        print "Image %s does not contain a WCS" % this_image
        data = data[1576:1776, 1166:1366]

    except StampError:
        print "Image %s does not contain the target. The center of the image is being used instead." % this_image
        data = data[1576:1776, 1166:1366]

    (sky, niter) = img_scale.sky_median_sig_clip(data, 0.01, 0.1, 10)
    small_images.append(
        img_scale.sqrt(data, scale_min=sky - 100, scale_max=sky + 5000))

# Define the canvas properties
fig = py.figure(figsize=(15, 7.5))
fig.subplots_adjust(hspace=0.15,
                    wspace=0,
                    top=0.95,
                    bottom=0.01,
                    left=0.0,
                    right=1.0)

# Render mosaic
for index in range(len(files)):
    a = fig.add_subplot(2, 5, camera_subplot_index(files[index]))
    py.axis('off')
    py.imshow(small_images[index], aspect='equal', cmap=cm.Greys)
# Get image names from the command line
files = args.files
if not files:
    sys.stderr.write('Error: no files found')
    sys.exit(1)

# Load the image
this_image = files[0]
print "Processing %s" % this_image
f = fits.open(this_image)
d, h2 = f[0].data, f[0].header

# Rescale the image
(sky, niter) = img_scale.sky_median_sig_clip(d, 0.01, 0.1, 10)
processed_image = img_scale.sqrt(d, scale_min=sky - 300, scale_max=sky + 10000)

# Get basic data in the original frame
w2 = wcs.WCS(h2)

# To make the rotation easier, first shift the WCS reference pixel to
# the center of the grid
nx, ny = h2["naxis1"], h2["naxis2"]
i0, j0 = (float(nx) + 1.0) / 2, (float(ny) + 1.0) / 2
[ra0, dec0], = w2.wcs_pix2world([[i0, j0]], 1)
h2.update(crpix1=i0, crpix2=j0, crval1=ra0, crval2=dec0)

# Now construct a header that is in the equatorial frame (North up, east to the left)
h1 = h2.copy()
h1.update(cd1_1=-np.hypot(h2["CD1_1"], h2["CD1_2"]),
          cd1_2=0.0,
Beispiel #18
0
def fitsToImage(r,
                g=None,
                b=None,
                outputFilename='/tmp/out.jpeg',
                nsigma=10.0,
                rFudge=1.0,
                gFudge=1.0,
                bFudge=1.0,
                minFudge=0.0,
                imageQuality=100,
                imageCoreSizePercent=10,
                useCoreStats=False,
                excludeZeros=True,
                magicNumber=0):
    """
    Generic code to convert FITS files into PNG or JPEG. If three images are provided the code will attempt to build a colour image.
    """
    import img_scale
    from PIL import Image

    if g is None:
        g = r

    if b is None:
        b = r

    print("Loading r image...")
    r_img = pf.getdata(r)
    (dataStdDev, dataMedian, maskedPixelRatio, maskedPixelRatioAtCore,
     coreStdDev, coreMedian) = getFITSImageStats2(
         image=r_img,
         imageCoreSizePercent=imageCoreSizePercent,
         excludeZeros=excludeZeros,
         magicNumber=magicNumber)
    if useCoreStats:
        rminval = coreMedian - coreStdDev * minFudge
        rmaxval = coreMedian + (nsigma * coreStdDev) * rFudge
    else:
        rminval = dataMedian - dataStdDev * minFudge
        rmaxval = dataMedian + (nsigma * dataStdDev) * rFudge

    print("Loading g image...")
    g_img = pf.getdata(g)
    (dataStdDev, dataMedian, maskedPixelRatio, maskedPixelRatioAtCore,
     coreStdDev, coreMedian) = getFITSImageStats2(
         image=g_img,
         imageCoreSizePercent=imageCoreSizePercent,
         excludeZeros=excludeZeros,
         magicNumber=magicNumber)
    if useCoreStats:
        gminval = coreMedian - coreStdDev * minFudge
        gmaxval = coreMedian + (nsigma * coreStdDev) * gFudge
    else:
        gminval = dataMedian - dataStdDev * minFudge
        gmaxval = dataMedian + (nsigma * dataStdDev) * gFudge

    print("Loading b image...")
    b_img = pf.getdata(b)
    (dataStdDev, dataMedian, maskedPixelRatio, maskedPixelRatioAtCore,
     coreStdDev, coreMedian) = getFITSImageStats2(
         image=b_img,
         imageCoreSizePercent=imageCoreSizePercent,
         excludeZeros=excludeZeros,
         magicNumber=magicNumber)
    if useCoreStats:
        bminval = coreMedian - coreStdDev * minFudge
        bmaxval = coreMedian + (nsigma * coreStdDev) * bFudge
    else:
        bminval = dataMedian - dataStdDev * minFudge
        bmaxval = dataMedian + (nsigma * dataStdDev) * bFudge

    print("New image being created...")
    img = zeros((b_img.shape[0], b_img.shape[1], 3), dtype=float)

    img[:, :, 0] = clip(
        flipud(img_scale.sqrt(r_img, scale_min=rminval, scale_max=rmaxval)) *
        255.0, 0.0, 255.0)  #red
    img[:, :, 1] = clip(
        flipud(img_scale.sqrt(g_img, scale_min=gminval, scale_max=gmaxval)) *
        255.0, 0.0, 255.0)  #green
    img[:, :, 2] = clip(
        flipud(img_scale.sqrt(b_img, scale_min=bminval, scale_max=bmaxval)) *
        255.0, 0.0, 255.0)  #blue

    print("Converting array to uint8...")
    img = img.astype(uint8)

    if (b_img.shape[0] * b_img.shape[1] * 3) > 2**32:
        print("Generating Image object...")
        # size of image x size of image x 3 layers > 2^32.  We need to split into quarters.
        imgObject = Image.fromarray(img[0:b_img.shape[0] / 2,
                                        0:b_img.shape[1] / 2, :])
        print("Saving image...")
        imgObject.save("01%s" % (outputFilename), quality=imageQuality)
        imgObject = Image.fromarray(img[b_img.shape[0] / 2:b_img.shape[0],
                                        0:b_img.shape[1] / 2, :])
        print("Saving image...")
        imgObject.save("02%s" % (outputFilename), quality=imageQuality)
        imgObject = Image.fromarray(img[0:b_img.shape[0] / 2,
                                        b_img.shape[1] / 2:b_img.shape[1], :])
        print("Saving image...")
        imgObject.save("03%s" % (outputFilename), quality=imageQuality)
        imgObject = Image.fromarray(img[b_img.shape[0] / 2:b_img.shape[0],
                                        b_img.shape[1] / 2:b_img.shape[1], :])
        print("Saving image...")
        imgObject.save("04%s" % (outputFilename), quality=imageQuality)

    else:
        # The image is small enough to deal with in a single go...
        print("Saving image...")
        imgObject = Image.fromarray(img)
        imgObject.save(outputFilename, quality=imageQuality)

    return maskedPixelRatio, maskedPixelRatioAtCore
Beispiel #19
0
def transform(imloc, ra_center, dec_center, radial_extent, vmax=1.5):

    """ Rescale and trim input image. """

    hdu = fits.open(imloc)
    im = hdu[0].data
    thisisalma = False
    if im.ndim == 4:
        thisisalma = True
        im = im[0, 0, :, :]
    optical_header = hdu[0].header
    bad = im * 0 != 0
    good = im * 0 == 0
    im[bad] = im[good].min()

    # compute the (x, y) center and pixel scale in the optical image
    wcs_optical = wcs.WCS(optical_header, naxis=2)
    pixxy = wcs_optical.wcs_world2pix(ra_center, dec_center, 1)
    x_optical = numpy.round(pixxy[0])
    y_optical = numpy.round(pixxy[1])
    headerkeys = optical_header.keys()
    cd1_1 = headerkeys.count('CD1_1')
    if cd1_1 == 0:
        cdelt1_optical = numpy.abs(optical_header['CDELT1'] * 3600)
        cdelt2_optical = numpy.abs(optical_header['CDELT2'] * 3600)
    else:
        cdelt1_optical = numpy.abs(optical_header['CD1_1'] * 3600)
        cdelt2_optical = numpy.abs(optical_header['CD2_2'] * 3600)
        cd11 = optical_header['CD1_1']
        cd12 = optical_header['CD1_2']
        cd21 = optical_header['CD2_1']
        cd22 = optical_header['CD2_2']
        cdelt1_optical = numpy.sqrt(cd11 ** 2 + cd12 ** 2) * 3600
        cdelt2_optical = numpy.sqrt(cd21 ** 2 + cd22 ** 2) * 3600
        if cd12 == 0:
            cd12 = cd11 / 1e8
        cdratio = numpy.abs(cd11 / cd12)
        if cdratio < 1:
            cdratio = 1 / cdratio
        #if cdratio < 1e2:
            #print "This shit ain't rotated yo!"
            #import pdb; pdb.set_trace()
    x_extent = numpy.round(radial_extent / cdelt1_optical)
    y_extent = numpy.round(radial_extent / cdelt2_optical)
    nx = im[:, 0].size
    ny = im[0, :].size

    #angularradius = 0.5 * 60
    #pixscale = numpy.sqrt(cdelt1_optical * cdelt2_optical)
    #pixradius = numpy.round(angularradius / pixscale).astype(int)
    #x1 = str(x_optical.astype(int) - pixradius)
    #x2 = str(x_optical.astype(int) + pixradius)
    #y1 = str(y_optical.astype(int) - pixradius)
    #y2 = str(y_optical.astype(int) + pixradius)
    #region = '[' + x1 + ':' + x2 + ',' + y1 + ':' + y2 + ']'
    #cutfile = 'fitscutouts/' + dataname + '_' + ifilt + '_cut.fits'
    #cmd = 'imcopy ' + optloc + region + ' ' + cutfile
    #print cmd
    
    # make the trimmed optical image
    #if dataname == 'XMM109':
    #    optical_trimmed = numpy.ones([2 * y_extent, 2 * x_extent])
    #else:
    if (x_optical - x_extent < 0) | (x_optical + x_extent > nx) | \
            (y_optical - y_extent < 0) | (y_optical + y_extent > ny):
        # pad with zeros
        import pdb; pdb.set_trace()
        trimmed = numpy.zeros([2 * y_extent, 2 * x_extent])
        nx_pad = trimmed[0, :].size
        ny_pad = trimmed[:, 0].size
        if x_optical - x_extent < 0:
            xr0 = 0
            xrr0 = x_extent - x_optical
        else:
            xr0 = x_optical - x_extent
            xrr0 = 0
        if y_optical - y_extent < 0:
            yr0 = 0
            yrr0 = y_extent - y_optical
        else:
            yr0 = y_optical - y_extent
            yrr0 = 0
        if x_optical + x_extent > nx:
            xr1 = nx
            xrr1 = nx_pad / 2 + (nx - x_optical)
        else:
            xr1 = x_optical + x_extent
            xrr1 = nx_pad
        if y_optical + y_extent > ny:
            yr1 = ny
            yrr1 = ny_pad / 2 + (ny - y_optical)
        else:
            yr1 = y_optical + y_extent
            yrr1 = ny_pad
        trimmed[yrr0:yrr1, xrr0:xrr1] = im[yr0:yr1, xr0:xr1]
    else:
        xr0 = x_optical - x_extent
        yr0 = y_optical - y_extent
        xr1 = x_optical + x_extent
        yr1 = y_optical + y_extent
        trimmed = im[yr0:yr1, xr0:xr1]
    #print(vmax)
    if not thisisalma:
        trimmed -= trimmed.min()# - 1
        trimmed = img_scale.sqrt(trimmed, scale_max=vmax)
        #trimmed *= 2.5
        #trimmed = numpy.sqrt(trimmed)
        #trimmed -= trimmed.min()
        #trimmedsort = numpy.sort(trimmed).flatten()
        #ntrimmed = trimmedsort.size
        #vmax = trimmedsort[0.99999 * ntrimmed]
        #vmin = trimmedsort[0.5 * ntrimmed]
        #print(vmin, vmax)
        #toohigh = trimmed > vmax
        #toolow = trimmed < vmin
        #trimmed[toolow] = vmin
        #trimmed[toohigh] = vmax
    return trimmed
# Get image names from the command line
files = args.files
if not files:
    sys.stderr.write("Error: no files found")
    sys.exit(1)

# Load the image
this_image = files[0]
print "Processing %s" % this_image
f = fits.open(this_image)
d, h2 = f[0].data, f[0].header

# Rescale the image
(sky, niter) = img_scale.sky_median_sig_clip(d, 0.01, 0.1, 10)
processed_image = img_scale.sqrt(d, scale_min=sky - 300, scale_max=sky + 10000)

# Get basic data in the original frame
w2 = wcs.WCS(h2)

# To make the rotation easier, first shift the WCS reference pixel to
# the center of the grid
nx, ny = h2["naxis1"], h2["naxis2"]
i0, j0 = (float(nx) + 1.0) / 2, (float(ny) + 1.0) / 2
[ra0, dec0], = w2.wcs_pix2world([[i0, j0]], 1)
h2.update(crpix1=i0, crpix2=j0, crval1=ra0, crval2=dec0)

# Now construct a header that is in the equatorial frame (North up, east to the left)
h1 = h2.copy()
h1.update(
    cd1_1=-np.hypot(h2["CD1_1"], h2["CD1_2"]),