def get_radec(self, edgebuffer=60, flagmax=1): print "Randomly picks RA, DEC for each fake source from the high-res image..." # hdr = pyfits.getheader(self.realimages[self.bands[0]]) # self.wcs = pywcs.WCS(hdr) hdr_hires = pyfits.getheader(self.realimages[self.bands[0]]) hdr_lores = pyfits.getheader(self.realimages[self.bands[1]]) self.wcs_hires = pywcs.WCS(hdr_hires) self.wcs_lores = pywcs.WCS(hdr_lores) flag_img = pyfits.getdata(self.flagimages[self.bands[0]]) x0 = edgebuffer / 2. y0 = edgebuffer / 2. x1 = self.xmax - edgebuffer / 2. y1 = self.ymax - edgebuffer / 2. ra0, dec0 = self.wcs_hires.wcs_pix2sky([[x0, y0]], 1)[0] ra1, dec1 = self.wcs_hires.wcs_pix2sky([[x1, y1]], 1)[0] ra_arr = np.zeros(self.ngal) dec_arr = np.zeros(self.ngal) for i in range(self.ngal): offimage = 1 while offimage: ra = np.random.uniform(ra0, ra1) dec = np.random.uniform(dec0, dec1) x, y = self.wcs_hires.wcs_sky2pix([[ra, dec]], 1)[0] if fg.test_flag(x, y, flag_img) < flagmax: offimage = 0 ra_arr[i] = ra dec_arr[i] = dec self.ra = ra_arr self.dec = dec_arr return ra_arr, dec_arr
def __init__(self, input_image, ref_image, input_rms, ref_rms, input_flg, ref_flg, coofile): ### Initialization self.input_image = input_image self.ref_image = ref_image self.input_rms = input_rms self.ref_rms = ref_rms self.input_seg = input_rms.replace('rms', 'geo_seg') self.ref_seg = ref_rms.replace('rms', 'geo_seg') self.input_flg = input_flg self.ref_flg = ref_flg self.input_cat = os.path.splitext(self.input_image)[0] + '.cat' self.ref_cat = os.path.splitext(self.ref_image)[0] + '.cat' # initialize WCS info self.hdr_ref = pyfits.getheader(self.ref_image) self.wcs_ref = pywcs.WCS(self.hdr_ref) if self.hdr_ref.has_key('cd1_1'): cd1_1 = self.hdr_ref['cd1_1'] if self.hdr_ref.has_key('cd1_2'): cd1_2 = self.hdr_ref['cd1_2'] else: cd1_2 = 0. self.ref_pixscale = 3600. * np.sqrt(cd1_1**2 + cd1_2**2) else: self.ref_pixscale = np.abs(self.hdr_ref['cdelt1']) * 3600. # Also find x0ref_old, y0ref_old self.hdr_in = pyfits.getheader(self.input_image) cd1_1 = self.hdr_in['cd1_1'] if self.hdr_in.has_key('cd1_2'): cd1_2 = self.hdr_in['cd1_2'] else: cd1_2 = 0. self.input_pixscale = np.sqrt(cd1_1**2 + cd1_2**2) * 3600. self.wcs_in = pywcs.WCS(self.hdr_in) self.coofile = coofile
def cutout_30mas_v1(h_seg, v_drz): """ Because the v1.0, 30mas version of the F606W mosaic includes the parallel fields and therefore covers a larger area than the CANDELS footprint (defined by the v0.5 mosaic), I am making a cutout from the 30mas mosaic to cover the same area as the v0.5 60mas mosaics. """ hdr1 = pyfits.getheader(h_seg) hdr2 = pyfits.getheader(v_drz) nx1 = hdr1['naxis1'] ny1 = hdr1['naxis2'] # Now calculate the corners of the cutout in the 30mas frame; 1=60mas frame, # 2 = 30mas frame wcs1 = pywcs.WCS(hdr1) wcs2 = pywcs.WCS(hdr2) sky00 = wcs1.wcs_pix2sky([[1, 1]], 1) corner00 = np.floor(wcs2.wcs_sky2pix(sky00, 1)).astype('int')[0] sky11 = wcs1.wcs_pix2sky([[nx1, ny1]], 1) corner11 = np.ceil(wcs2.wcs_sky2pix(sky11, 1)).astype('int')[0] xlo, ylo = corner00 xhi, yhi = corner11 print "xlo, xhi, ylo, yhi", xlo, xhi, ylo, yhi output = os.path.splitext(v_drz)[0] + '_center.fits' v_drz_array = pyfits.getdata(v_drz) v_drz_hdr = pyfits.getheader(v_drz) v_drz_hdr['crpix1'] = v_drz_hdr['crpix1'] - xlo v_drz_hdr['crpix2'] = v_drz_hdr['crpix2'] - ylo v_drz_array_new = v_drz_array[ylo:yhi + 1, xlo:xhi + 1] pyfits.append(output, v_drz_array_new, v_drz_hdr)
def transform_pixcoord(source, dest): """ Transform the pixel coordinates from the source image to the dest(ination) image. """ wcs_src = pywcs.WCS(pyfits.getheader(source)) wcs_dest = pywcs.WCS(pyfits.getheader(dest)) coord_src = flatten_pixcoord(source) sky_src = wcs_src.wcs_pix2sky(coord_src, 1) coord_dest = wcs_dest.wcs_sky2pix(sky_src, 1) return np.around(coord_dest).astype('int')
def checkast(imglist): import agnkey import pywcs from numpy import median, array, compress, abs, std, argmin, isnan, sqrt hdr0 = agnkey.util.readhdr(imglist[0]) # ###### check with sources the accuracy of the astrometry wcs = pywcs.WCS(hdr0) xpix, ypix, fw, cl, cm, ell, bkg = agnkey.agnastrodef.sextractor( imglist1[0]) pixref = array(zip(xpix, ypix), float) sky0 = wcs.wcs_pix2sky(pixref, 1) max_sep = 10 for img in imglist1: xsex, ysex, fw, cl, cm, ell, bkg = agnkey.agnastrodef.sextractor( img) # sextractor hdr1 = agnkey.util.readhdr(img) wcs1 = pywcs.WCS(hdr1) pix1 = wcs1.wcs_sky2pix(sky0, 1) xpix1, ypix1 = zip(*pix1) # pixel position of the obj in image 0 xdist, ydist = [], [] for i in range(len(xpix1)): dist = sqrt((xpix1[i] - xsex)**2 + (ypix1[i] - ysex)**2) idist = argmin(dist) if dist[idist] < max_sep: xdist.append(xpix1[i] - xsex[idist]) ydist.append(ypix1[i] - ysex[idist]) xoff, xstd = round(median(xdist), 2), round(std(xdist), 2) yoff, ystd = round(median(ydist), 2), round(std(ydist), 2) _xdist, _ydist = array(xdist), array(ydist) __xdist = compress( (abs(_xdist - xoff) < 3 * xstd) & (abs(_ydist - yoff) < 3 * ystd), _xdist) __ydist = compress( (abs(_xdist - xoff) < 3 * xstd) & (abs(_ydist - yoff) < 3 * ystd), _ydist) xoff, xstd = round(median(__xdist), 2), round(std(__xdist), 2) yoff, ystd = round(median(__ydist), 2), round(std(__ydist), 2) if isnan(xoff): xoff, xstd = 0, 0 if isnan(yoff): yoff, ystd = 0, 0 print xoff, xstd, len(__xdist) print yoff, ystd #if abs(xoff)>=1: agnkey.updateheader(img, 0, { 'CRPIX1': [hdr1['CRPIX1'] - xoff, 'Value at ref. pixel on axis 1'] }) #if abs(yoff)>=1: agnkey.updateheader(img, 0, { 'CRPIX2': [hdr1['CRPIX2'] - yoff, 'Value at ref. pixel on axis 2'] })
def __init__(self, paramfile, clean=True, sample='highz'): c = yaml.load(open(paramfile, 'rb')) self.c = c self.paramfile = paramfile for k in c.keys(): setattr(self, k, c[k]) print self.paramfile if not self.hires_drz.endswith('_drz.fits'): print "Warning: should rename the high-res science image to the format of *_drz.fits!" self.hr_root = os.path.splitext(self.hires_drz)[0][:-4] if not self.lores_drz.endswith('_drz.fits'): print "Warning: should rename the low-res science image to the format of *_drz.fits!" self.lr_root = os.path.splitext(c['lores_drz'])[0][:-4] self.objnames = np.array(self.targets.keys()) self.objectid = np.array([self.targets[k][0] for k in self.objnames]) self.ra = np.array([self.targets[k][1] for k in self.objnames]) self.dec = np.array([self.targets[k][2] for k in self.objnames]) if type(self.bkgd_boxsize) == type(1.0): self.bkgd_boxpix = self.bkgd_boxsize / self.lores_scale else: self.bkgd_boxpix = np.array(self.bkgd_boxsize) / self.lores_scale # The size of background box in low-res pixels if type(self.fit_boxsize) == type(1.0): self.fit_boxpix = self.fit_boxsize / self.hires_scale else: self.fit_boxpix = np.array(self.fit_boxsize) / self.hires_scale self.hdr_lores = pyfits.getheader( os.path.join(self.loresdir, self.lores_drz)) self.hdr_hires = pyfits.getheader( os.path.join(self.hiresdir, self.hires_drz)) # need WCS information in the low-res image to find the object by RA, DEC self.hr_wcs = pywcs.WCS(self.hdr_hires) self.lr_wcs = pywcs.WCS(self.hdr_lores) self.today = time.strftime('%y%m%d') self.lores_err_obj = [''] * len(self.targets) self.psfroot = os.path.splitext(self.psffile)[0] # self.find_matches() self.read_positions() self.hr_flag_obj = {} # dictionaries to store the TFIT results self.mag = {} self.magerr = {} self.sigbkgd = {} self.medbkgd = {} self.chi2nu = {} self.avg_resid = {} self.med_resid = {} self.sample = sample
def match_diagnostic_plot(root='JKCS041-2r-168-F160W'): """ Make delta_x delta_y scatter plot and vector diagram for outputs from the alignment script. """ import pywcs drz = pyfits.getheader(root + '_drz.fits', 'SCI') wcs = pywcs.WCS(drz) x_ref, y_ref, x_in, y_in, i_ref, i_in = np.loadtxt(root + '_align.match', unpack=True) dx = x_in - x_ref dy = y_in - y_ref plt.scatter(dx, dy, alpha=0.1) plt.xlim(-3, 3) plt.ylim(-3, 3) s = 200 plt.quiver(x_in, y_in, dx * s, dy * s, scale=1, units='xy', alpha=0.5) plt.quiver(0.05 * x_in.max(), 0.05 * y_in.max(), s, 0, scale=1, units='xy', alpha=0.8, label='1 pix', color='red') plt.legend()
def GetImageCoords(args): import pyfits header = pyfits.open(args.image)[args.imageext].header wcs = pywcs.WCS(header) wcoords = np.dstack((args.ra,args.dec))[0] pcoords = wcs.wcs_sky2pix(wcoords, 1) return pcoords
def image_limits(hdr): """ Function to get the image limites in wcs Input - hdr pyfits_hdr : image hdr Output - #FIXME - finish documentation """ im_wcs = pywcs.WCS(hdr) pixcrd = np.array([[0, 0]], np.float_) coor1 = im_wcs.wcs_pix2sky([[0, 0]], 1) coor2 = im_wcs.wcs_pix2sky([[hdr["NAXIS1"], hdr["NAXIS2"]]], 1) coor3 = im_wcs.wcs_pix2sky([[0, hdr["NAXIS2"]]], 1) coor4 = im_wcs.wcs_pix2sky([[hdr["NAXIS1"], 0]], 1) c0min = min([coor1[0][0], coor2[0][0], coor3[0][0], coor4[0][0]]) c0max = max([coor1[0][0], coor2[0][0], coor3[0][0], coor4[0][0]]) c1min = min([coor1[0][1], coor2[0][1], coor3[0][1], coor4[0][1]]) c1max = max([coor1[0][1], coor2[0][1], coor3[0][1], coor4[0][1]]) return [c0min, c0max], [c1min, c1max]
def cutout(image, ra, dec, xwidth, ywidth, scale): """ Make a cutout around position (ra, dec) with the dimensions of the cutout being (xwidth, ywidth). image: file name of the image ra, dec: sky coordinates of the center of cutout, in degrees xwidth, ywidth: dimensions of the cutout, **in arcsec** scale: pixel scale of the input image, **in arcsec** """ hdr = pyfits.getheader(image) # First calculate the image coordinates, based on 1-indexing wcs = pywcs.WCS(hdr) xypos = wcs.wcs_sky2pix([[ra, dec]], 1)[0] xc = int(round(xypos[0])) yc = int(round(xypos[1])) xw_pix = int(round(xwidth / (2. * scale))) yw_pix = int(round(ywidth / (2. * scale))) xmin = xc - xw_pix xmax = xc + xw_pix ymin = yc - yw_pix ymax = yc + yw_pix outname = raw_input('Please give the file name of the output image: ') if not len(outname): outname = 'cutout.fits' print "No file name is given; use cutout.fits" if os.path.exists(outname): os.remove(outname) iraf.imcopy(image + '[%d:%d,%d:%d]' % (xmin, xmax, ymin, ymax), outname)
def getFITSInfo(fn): """Parse the FITS header for pointing and pixel size information return [RA,DEC], pixel resolution, pixel of [RA,DEC] generates a WCS instance for converting between sky and pixels """ hdulist = pf.open(fn) hdr = hdulist[0].header #CTYPE1: RA---[PROJ], projection SIN/TAN/ARC #CRVAL1: reference RA position in degrees #CRPIX1: location of reference pixel #CDELT1: delta RA/pixel size in degrees #CTYPE2: DEC--[PROJ], projection SIN/TAN/ARC #CRVAL2: reference DEC position in degrees #CRPIX2: location of reference pixel #CDELT2: delta DEC/pixel size in degrees #LATPOL: latitude of array centre ra = hdr['CRVAL1'] dra = hdr['CDELT1'] raPix = hdr['CRPIX1'] dec = hdr['CRVAL2'] ddec = hdr['CDELT2'] decPix = hdr['CRPIX2'] latPole = hdr.get('LATPOLE', hdr['CRVAL2']) #CTYPE3: FREQ #CRVAL3: centre bandwidth in Hz #CRPIX3: number of freq channels #CDELT3: bandwith of channel centreFreq = hdr['CRVAL3'] nchans = int(hdr['CRPIX3']) bw = hdr['CDELT3'] #CTYPE4: STOKES #CRVAL4: number of Stokes values #CRPIX4: Initial Stokes label (1:I 2:Q 3:U 4:V) #CDELT4: Stokes label step size nstokes = hdr['CRVAL4'] stokes0 = hdr['CRPIX4'] #Generate a WCS structure, using the normal method creates errors due to header formating wcs = pywcs.WCS(naxis=2) wcs.wcs.crval = [ra, dec] wcs.wcs.crpix = [raPix, decPix] wcs.wcs.cdelt = [dra, ddec] wcs.wcs.ctype = ["RA---SIN", "DEC--SIN"] hdulist.close() return { 'hdr': hdr, 'ra': ra, 'dec': dec, 'dra': dra, 'ddec': ddec, 'raPix': raPix, 'decPix': decPix, 'latPole': latPole, 'wcs': wcs, 'centreFreq': centreFreq, 'nchans': nchans, 'bw': bw, 'nstokes': nstokes, 'stokes0': stokes0 }
def coord2pix(p_list, header): """ return corresponding image pixel, given coordinate Utility: - to get lens center in pixel of image (corresponding to the input vis), based on coordinates - to get source pos in pixel of image Parameters ---------- p_list: list of coords in astrolib.coords object Returns ------- ra_px, dec_px """ import pywcs ra_px_list = [] dec_px_list = [] wcs = pywcs.WCS(header).sub([1, 2]) for p1 in p_list: ra, dec = p1 ra_px, dec_px = wcs.wcs_sky2pix(ra, dec, 1) ra_px_list.append(ra_px[0]) dec_px_list.append(dec_px[0]) return ra_px_list, dec_px_list
def apphot(hdu, glon, glat, rad_as=60, outerrad_as=120, return_profile=False): img = hdu[0].data img[img != img] = 0 header = hdu[0].header wcs = pywcs.WCS(header) xc, yc = wcs.wcs_sky2pix(glon, glat, 0) nr, rr, rprof = azimuthalAverage(img, return_nr=True, center=[xc, yc]) bmaj = float(header['BMAJ']) bmin = float(header['BMIN']) cdelt1, cdelt2 = wcs.wcs.cdelt[:2] cd1 = cdelt1 * wcs.wcs.cd[0, 0] cd2 = cdelt2 * wcs.wcs.cd[1, 1] ppbeam = 2 * numpy.pi * bmin * bmaj / abs(cd1 * cd2) / (8 * numpy.log(2)) rr_as = (rr) * numpy.abs(cd1) * 3600.0 nr_cum = nr.cumsum() phot = (rprof * nr).cumsum() / ppbeam inner_ind = numpy.argmin(numpy.abs(rr_as - rad_as)) outer_ind = numpy.argmin(numpy.abs(rr_as - outerrad_as)) inner_ap = phot[inner_ind] outer_ap = (phot[outer_ind] - phot[inner_ind]) / ( nr_cum[outer_ind] - nr_cum[inner_ind]) * nr_cum[inner_ind] if return_profile: return rr_as, phot, inner_ap - outer_ap, outer_ap else: return inner_ap - outer_ap, outer_ap
def has_wcs(filename=None, header=None): if not header: header = pyfits.getheader(filename, -1) w = pywcs.WCS(header=header) return w.wcs.has_cd()
def a1600_pixtosky(angle_d, pixcrd, origin): """ Convert input pixel coordinates to sky coordinates for NIRSpec A1600 aperture. Keyword arguments: angle_d -- Degree angle rotation between the aperture grid and the sky coordinates. pixcrd -- Pixel coordinates to be converted. Can be a single coordinate in the form (x_pix, y_pix), or a numpy array of coordinates. origin -- Origin of the target coordinate system. Output(s): world - Computed sky coordinates, rounded to nearest 1. The final coordinates are relative to grid dimensions. Output dimensions match those of input. """ # Change angle from degrees to radians angle_r = np.radians(angle_d) # Create a new WCS object of two axes wcs = pywcs.WCS(naxis=2) # Setup a pixel projection wcs.wcs.crpix = [7.5, 7.5] wcs.wcs.crval = [321.536442, 5.689362] wcs.wcs.cdelt = np.array([0.106841547, 0.108564798]) wcs.wcs.pc = ([np.sin(angle_r),np.cos(angle_r)], [np.cos(angle_r),-np.sin(angle_r)]) # Calculate new coordinates for each pair of input coordinates sky_coords = wcs.wcs_pix2sky(pixcrd, origin) return sky_coords
def get_frames_with_target(myfile, ra, dec, debug=False): hdulist = pf.open(myfile) if len(hdulist)>1: indices = np.arange(len(hdulist)-1)+1 else: indices = np.array([0]) frames = [] for i in indices: prihdr = hdulist[i].header img = hdulist[i].data * 1. ny, nx = img.shape if (ra * dec != 0): # Get pixel coordinates of SN wcs = pywcs.WCS(prihdr) try: target_pix = wcs.wcs_sky2pix([(np.array([ra,dec], np.float_))], 1)[0] except: print "ERROR when converting sky to wcs. Is astrometry in place? Default coordinates assigned." target_pix = [+nx/2., ny/2.] if debug: print i, target_pix else: target_pix = [+nx/2., ny/2.] if (target_pix[0] > 0 and target_pix[0]<nx) and (target_pix[1] > 0 and target_pix[1]<ny): frames.append(i) return np.array(frames)
def postage2(directory, i, ra, dec, nn_ra=None, nn_dec=None, maj=None, min=None, pa=None): ''' Making the cutouts with plt.imshow ''' image = '/net/reusel/data1/osinga/button_classification/' + directory + '/source' + str( i) + '.fits' hdulist = pf.open(image) data = hdulist[0].data fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.2) wcs = pw.WCS(hdulist[0].header) pixsize = abs(wcs.wcs.cdelt[0]) pixsize = pixsize * 3600 # 1 pixel corresponds to 1.5 arcsec now z1, z2 = zscale(data) plt.imshow(data, clim=(z1, z2), origin='lower', cmap='gray') skycrd = np.array([[ra, dec, 0, 0]], np.float_) pixel = wcs.wcs_sky2pix(skycrd, 1) if nn_ra: plt.title('Nearest Neighbour sources') # plot the first source plt.scatter(pixel[0][0], pixel[0][1], s=4) # and it's nearest neighbour skycrd = np.array([[nn_ra, nn_dec, 0, 0]], np.float_) pixel = wcs.wcs_sky2pix(skycrd, 1) plt.scatter(pixel[0][0], pixel[0][1], s=4) else: plt.title('Multiple Gaussian source') ellipse = Ellipse((pixel[0][0], pixel[0][1]), 2 * maj / pixsize, 2 * min / pixsize, angle=pa, fill=False) ax.add_artist(ellipse) callback = Index() ax1 = plt.axes([0.2, 0.05, 0.1, 0.075]) ax2 = plt.axes([0.5, 0.05, 0.1, 0.075]) ax3 = plt.axes([0.8, 0.05, 0.1, 0.075]) button1 = Button(ax1, 'Single') button1.on_clicked(callback.single) button2 = Button(ax2, 'Double') button2.on_clicked(callback.double) button3 = Button(ax3, 'Unclassified') button3.on_clicked(callback.unclassified) plt.show()
def get_ra_dec_limits(image): """ This function reads RA and DEC values correponding to the spatial limits of the sky image. Input: - image <str>: name of image(tile) fits file. Output: - ra,dec <tuple>: two tuples with image sky region limits. """ hdr = pyfits.getheader(image) wcs = pywcs.WCS(hdr) naxis1 = hdr['NAXIS1'] naxis2 = hdr['NAXIS2'] ra_centre = hdr['CRVAL1'] dec_centre = hdr['CRVAL2'] pixcrd = numpy.array([[1, 1], [naxis1, naxis2]]) skycrd = wcs.wcs_pix2sky(pixcrd, 1) ra_min = skycrd[0][0] dec_min = skycrd[0][1] ra_max = skycrd[1][0] dec_max = skycrd[1][1] return ((ra_min, ra_max), (dec_min, dec_max))
def genwcs(rac,decc,pixscal=11.7,sizes=[4096,4096]): """ rac: center ra, decc: center dec, pixscal: pixel scale in arcsec/pixel sizes: CCD pixels size, e.g. 1k= [1024,1024], 4k= [4096,4096] """ pixd= pixscal/3600. xc = sizes[0]/2. + 0.5 yc = sizes[1]/2. + 0.5 ddtm= S.zeros(sizes) wcs = pywcs.WCS() wcs.naxis1 = sizes[0] wcs.naxis2 = sizes[1] wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN'] wcs.wcs.crpix = S.array([xc,yc]) wcs.wcs.crval = S.array([rac,decc]) wcs.wcs.cd = S.array([[pixd,0],[0,pixd]]) wcs.wcs.cdelt = S.array([ 1., 1.]) hh = wcs.to_header() hh.update('IMAGEW',wcs.naxis1) hh.update('IMAGEH',wcs.naxis2) hdu = pyfits.PrimaryHDU(header=hh) return wcs
def _xy2radec(self, hdr, pix): ''' convert from xy to RADEC using the WCS from a FITS header ''' wcs = pywcs.WCS(hdr) radec = wcs.all_pix2sky([pix], 1) return radec.tolist()[0][0], radec.tolist()[0][1]
def wcs_polygon(fits_file, extension=1, use_pywcs=False): """ X, Y = wcs_polygon(fits_file, extension=1) Calculate a DS9/region polygon from WCS header keywords. Will try to use pywcs.WCS.calcFootprint if pywcs is installed. Otherwise will compute from header directly. """ ##### Open the FITS file hdulist = pyfits.open(fits_file) ##### Get the header try: sci = hdulist[extension].header except IndexError: print 'ERROR 3D-HST/wcs_polygon:\n'+\ 'Extension #%d out of range in %s' %(extension, fits_file) raise #### Try to use pywcs if it is installed pywcs_exists = True try: import pywcs except: pywcs_exists = False if pywcs_exists & use_pywcs: wcs = pywcs.WCS(sci) footprint = wcs.calcFootprint() regX = footprint[:, 0] regY = footprint[:, 1] return regX, regY #### Do it by hand if no pywcs NAXIS = [sci['NAXIS1'], sci['NAXIS2']] CRPIX = [sci['CRPIX1'], sci['CRPIX2']] CRVAL = [sci['CRVAL1'], sci['CRVAL2']] CD1_1 = sci['CD1_1'] CD2_2 = sci['CD2_2'] try: CD1_2 = sci['CD1_2'] CD2_1 = sci['CD2_1'] except: CD1_2 = 0. CD2_1 = 0. cosDec = np.cos(CRVAL[1] / 180 * np.pi) ##### Make region polygon from WCS keywords regX = CRVAL[0] + \ ((np.array([0,NAXIS[0],NAXIS[0],0])-CRPIX[0])*CD1_1 + (np.array([0,0,NAXIS[1],NAXIS[1]])-CRPIX[1])*CD1_2) / cosDec regY = CRVAL[1] + \ ((np.array([0,NAXIS[0],NAXIS[0],0])-CRPIX[0])*CD2_1 + (np.array([0,0,NAXIS[1],NAXIS[1]])-CRPIX[1])*CD2_2) return regX, regY
def wcs_swarp(image, crvals, pixscale): """pixscale is the desired pixel scale in arcsec.""" hdr = pyfits.getheader(image) wcs = pywcs.WCS(hdr) cdmatrix = np.array([[-1. * pixscale / 3600., 0.], [0., pixscale / 3600.]]) wcs.wcs.cd = cdmatrix crpix = wcs.wcs_sky2pix([crvals], 1) return crpix[0]
def GetImageCoords(args): with warnings.catch_warnings(): warnings.simplefilter("ignore") header = pyfits.open(args.image)[args.imageext].header wcs = pywcs.WCS(header) wcoords = np.dstack((args.ra,args.dec))[0] pcoords = wcs.wcs_world2pix(wcoords, 1) return pcoords
def finder(myfile,searchrad=0.2/60.): ra, dec = coordinates_conversor.hour2deg(fitsutils.get_par(myfile, "OBJRA"), fitsutils.get_par(myfile, "OBJDEC")) hdulist = pf.open(myfile)[0] img = hdulist.data * 1. img = img.T wcs = pywcs.WCS(hdulist.header) target_pix = wcs.wcs_sky2pix([(np.array([ra,dec], np.float_))], 1)[0] corner_pix = wcs.wcs_sky2pix([(np.array([ra,dec+searchrad], np.float_))], 1)[0] dx = int(np.abs(np.ceil(corner_pix[1] - target_pix[1]))) imgslice = img[int(target_pix[0])-2*dx:int(target_pix[0])+2*dx, int(target_pix[1])-2*dx:int(target_pix[1])+2*dx] #zmin, zmax = zscale.zscale() zmin = np.percentile(imgslice.flatten(), 5) zmax = np.percentile(imgslice.flatten(), 98) print "Min: %.1f, max: %.1f"%(zmin, zmax) gc = aplpy.FITSFigure(myfile, figsize=(10,9), north=True) gc.show_grayscale(vmin=zmin, vmax=zmax, smooth=1, kernel="gauss") gc.show_scalebar(0.1/60.) gc.scalebar.set_label('10 arcsec') gc.scalebar.set_color('white') gc.recenter(ra, dec, searchrad) #gc.show_markers(ra,dec+searchrad/20.,edgecolor='red',facecolor='none',marker="|",s=250, lw=10) #gc.show_markers(ra-(searchrad/20.)/np.cos(np.deg2rad(dec)),dec,edgecolor='red',facecolor='none',marker="_",s=250, lw=10) ras = np.array([ra , ra]) decs = np.array([dec, dec]) dxs = np.array([0, searchrad/10 / np.cos(np.deg2rad(dec))]) dys = np.array([searchrad/10, 0]) gc.show_arrows(ras, decs, dxs, dys, edgecolor="red", facecolor="red", head_width=0) ras = np.array([ra+searchrad*0.7/ np.cos(np.deg2rad(dec)), ra+searchrad*0.7/ np.cos(np.deg2rad(dec))]) decs = np.array([dec-searchrad*0.9, dec-searchrad*0.9]) dxs = np.array([0, searchrad/5 / np.cos(np.deg2rad(dec))]) dys = np.array([searchrad/5, 0]) gc.show_arrows(ras, decs, dxs, dys, edgecolor="k", facecolor="k") gc.add_label(ras[0]+dxs[0]*1.1, decs[0]+dys[0]*1.1, 'N', relative=False, color="k", horizontalalignment="center") gc.add_label(ras[1]+dxs[1]*1.1, decs[1]+dys[1]*1.1, 'E', relative=False, color="k", horizontalalignment="center") name = fitsutils.get_par(myfile, "NAME") filter = fitsutils.get_par(myfile, "FILTER") gc.add_label(0.05, 0.95, 'Object: %s'%(name), relative=True, color="white", horizontalalignment="left") gc.add_label(0.05, 0.9, 'Coordinates: RA=%s DEC=%s'%(coordinates_conversor.deg2hour(ra, dec)), relative=True, color="white", horizontalalignment="left") gc.add_label(0.05, 0.84, 'Filter: SDSS %s'%filter, relative=True, color="white", horizontalalignment="left") findername = 'finders/finder_%s_%s.jpg'%(name, filter) gc.save(findername) return findername
def generate_wcs(header_file): # Read in header header = generate_header(header_file) # Compute WCS object wcs = pywcs.WCS(header) return wcs