def to_fits(self, filename, format=None, clobber=False): if format is None: format = healpix.default_fits_format_codes[self.get_dtype().type] hdu0 = pyfits.PrimaryHDU() col0 = pyfits.Column(name='signal', format=format, array=self.map.map) col1 = pyfits.Column(name='weights', format=format, array=self.wgt.map) col_inds = [ pyfits.Column(name='sp_index%d' % n, format=format, array=i.map) for n, i in enumerate(self.ind) ] cols = pyfits.ColDefs([col0, col1] + col_inds) tbhdu = pyfits.new_table(cols) self.map._set_fits_header(tbhdu.header) hdulist = pyfits.HDUList([hdu0, tbhdu]) hdulist.writeto(filename, clobber=clobber)
def writefits(towrite, fname, no_lossy_compress=False, clobber=False): if type(towrite) == pf.PrimaryHDU: hlist = pf.HDUList(towrite) elif type(towrite) == pf.HDUList: hlist = towrite else: hlist = pf.HDUList(pf.PrimaryHDU(towrite)) if no_lossy_compress: if '.gz' in fname: hlist.writeto(os.path.splitext(fname)[0], clobber=clobber) else: hlist.writeto(fname, clobber=clobber) return if '.gz' in fname: n = os.path.splitext(fname)[0] else: n = fname hlist[0].data = UU.floatcompress(hlist[0].data) hlist.writeto(fname, clobber=clobber) os.system("gzip %s" % n)
def write_fits(self, fname): #Now write the FITS files prihdr = pyfits.Header() prihdr[ 'NPRESS'] = 'hello' #(len(pressures),'number of pressures, (mbar)') prihdr[ 'NTEMPS'] = 'hello3' #(len(temperatures),'number of temperatures, (K)') prihdr['NG'] = 'bye' #(ng,'number of quadrature nodes, weights') prihdr['NLAM'] = 'bye' #(len(wavelength),'number of wavelength, (um)') prihdr['SHIFT'] = 'bye' #(shift,'wavelength shift, (nm)') prihdu = pyfits.PrimaryHDU(np.array([1, 1]), header=prihdr) hdulist = pyfits.HDUList([prihdu]) hdulist.writeto(fname, clobber=True)
def test_fix_invalid_extname(self): phdu = fits.PrimaryHDU() ihdu = fits.ImageHDU() ihdu.header['EXTNAME'] = 12345678 hdul = fits.HDUList([phdu, ihdu]) assert_raises(fits.VerifyError, hdul.writeto, self.temp('temp.fits'), output_verify='exception') with CaptureStdio(): hdul.writeto(self.temp('temp.fits'), output_verify='fix') with fits.open(self.temp('temp.fits')): assert hdul[1].name == '12345678' assert hdul[1].header['EXTNAME'] == '12345678'
def test_insert_table_extension_to_empty_list(self): """Tests inserting a Simple Table ExtensionHDU to a empty HDUList.""" hdul = fits.HDUList() hdul1 = fits.open(self.data('tb.fits')) hdul.insert(0, hdul1[1]) info = [(0, 'PRIMARY', 'PrimaryHDU', 4, (), '', ''), (1, '', 'BinTableHDU', 24, '2R x 4C', '[1J, 3A, 1E, 1L]', '')] assert hdul.info(output=False) == info hdul.writeto(self.temp('test-insert.fits')) assert fits.info(self.temp('test-insert.fits'), output=False) == info
def test_insert_groupshdu_to_empty_list(self): """Tests inserting a Simple GroupsHDU to an empty HDUList.""" hdul = fits.HDUList() hdu = fits.GroupsHDU() hdul.insert(0, hdu) info = [(0, 'PRIMARY', 'GroupsHDU', 8, (), '', '1 Groups 0 Parameters')] assert hdul.info(output=False) == info hdul.writeto(self.temp('test-insert.fits')) assert fits.info(self.temp('test-insert.fits'), output=False) == info
def test_new_hdu_extname(self): """ Tests that new extension HDUs that are added to an HDUList can be properly indexed by their EXTNAME/EXTVER (regression test for ticket:48). """ f = fits.open(self.data('test0.fits')) hdul = fits.HDUList() hdul.append(f[0].copy()) hdul.append(fits.ImageHDU(header=f[1].header)) assert hdul[1].header['EXTNAME'] == 'SCI' assert hdul[1].header['EXTVER'] == 1 assert hdul.index_of(('SCI', 1)) == 1
def save(self, filepath): """Saves the SunPy Map object to a file. Currently SunPy can only save files in the FITS format. In the future support will be added for saving to other formats. Parameters ---------- filepath : string Location to save file to. """ pyfits_header = self.get_header().as_pyfits_header() hdu = pyfits.PrimaryHDU(self, header=pyfits_header) hdulist = pyfits.HDUList([hdu]) hdulist.writeto(os.path.expanduser(filepath))
def write_output_files(cube, params, inhead, typename): """ """ hdu_q = pyfits.PrimaryHDU(cube.real) try: generate_header(hdu_q, inhead, params) except: print "Warning: There was a problem generating the header, no " + \ "header information stored!" print "Unexpected error:", sys.exc_info()[0] hdu_q_list = pyfits.HDUList([hdu_q]) hdu_q_list.writeto(params.outputfn + '_' + typename + '_q.fits', clobber=True) hdu_main = pyfits.PrimaryHDU(cube.imag) try: generate_header(hdu_main, inhead, params) except: print "Warning: There was a problem generating the header, no " + \ "header information stored!" print "Unexpected error:", sys.exc_info()[0] hdu_list = pyfits.HDUList([hdu_main]) hdu_list.writeto(params.outputfn + '_' + typename + '_u.fits', clobber=True) hdu_p = pyfits.PrimaryHDU(abs(cube)) try: generate_header(hdu_p, inhead, params) except: print "Warning: There was a problem generating the header, no " + \ "header information stored!" print "Unexpected error:", sys.exc_info()[0] hdu_p_list = pyfits.HDUList([hdu_p]) hdu_p_list.writeto(params.outputfn + '_' + typename + '_p.fits', clobber=True)
def makeflat(self, outfile='flat.fits', indir='/data'): """Snap an exposure. Parameters: _outfile_: name of a calibration file to write _indir_: directory containing a bunch of FITS images """ self.logger.debug('Making flat-field calibration file.') buffer = numpy.zeros((self.height, self.width), 'Int32') count = 0 # For each fits file in this directory: # open it, and add the contents of all images to the buffer # count each buffer for fitsfile in glob.glob(indir + '/*.fits'): fits_f = pyfits.open(fitsfile, 'readonly') for hdu in fits_f: buffer += hdu.data count += 1 fits_f.close() # Make an array of the appropriate type and size, initialized to 0's pridata = numpy.zeros((self.height, self.width), 'Int16') pridata += (buffer / count) self.flatfield = pridata # Make the beginnings of a FITS file prihdu = pyfits.PrimaryHDU(pridata) hdulist = pyfits.HDUList([prihdu]) # Try to write out the file to disk name, ext = os.path.splitext(outfile) if ext == '': ext = '.fits' fitsfile = self.param.fitsdir + '/' + name + ext try: self.logger.debug('End calibration; writing fits file (%s)' % \ fitsfile) hdulist.writeto(fitsfile) except OSError, e: self.logger.error("Can't write file: %s" % fitsfile) return 1
def createfits(newfile, NX, NY, bitpix): """ Create a new simple FITS disk file of specified size and type; return the file ojbect in update mode. The header is minimal, and the data array is initialized to all zeros. """ if bitpix == 8: type = numpy.uint8 elif bitpix == 16: type = numpy.int16 elif bitpix == -16: type = numpy.uint16 elif bitpix == 32: type = numpy.int32 elif bitpix == -32: type = numpy.float32 elif bitpix == -64: type = numpy.float64 else: raise pyfits.FITS_SevereError, "Invalid BITPIX specification." # create object template in memory fobj = pyfits.HDUList() fobj.append(pyfits.PrimaryHDU()) # make data array -- NOTE! the numpy/pyfits indexing is backwards!! fobj[0].data = numpy.zeros((NY, NX), dtype=type) # fix up the header -- # actually, this no longer seems necessary with pyfits, but best safe fobj[0].header['BITPIX'] = bitpix fobj[0].header['NAXIS'] = 2 fobj[0].header.update('NAXIS1', NX, after="NAXIS") fobj[0].header.update('NAXIS2', NY, after="NAXIS1") if fobj[0].header.has_key('EXTEND'): del fobj[0].header.ascard['EXTEND'] # write the file to disk if os.path.isfile(newfile): os.remove(newfile) fobj.writeto(newfile) del fobj # reopen for updating, and return ff = pyfits.open(newfile, 'update') if ff[0].header['NAXIS1'] != NX or ff[0].header['NAXIS2'] != NY: raise pyfits.FITS_SevereError, "blech! nasty naxis bug!" return ff
def main(argv=sys.argv): parser = optparse.OptionParser(usage=usage) parser.add_option('-i', '--in', help='Input catalog name', dest='incatfile') parser.add_option('-c', '--cluster', help='Name of cluster', dest='cluster') parser.add_option('-o', '--out', help='name of output catalog', dest='outcatfile') parser.add_option('-d', '--nodust', help='Turn off dust correction', dest='doDust', action='store_false', default=True) options, args = parser.parse_args(argv) if options.incatfile is None: parser.error('Input catalog required!') if options.cluster is None: parser.error('Cluster Name is required!') if options.outcatfile is None: parser.error('Output catalog is required!') if len(args) != 1: parser.error('One catalog needed!') cat = ldac.openObjectFile(options.incatfile) if options.doDust: calibratedCat = photoCalibrateCat(cat, options.cluster) else: calibratedCat = photoCalibrateCat(cat, options.cluster, getDust=None) hdus = [pyfits.PrimaryHDU(), calibratedCat.hdu] hdus.extend(_transferOtherHDUs(options.incatfile)) hdulist = pyfits.HDUList(hdus) hdulist.writeto(options.outcatfile, clobber=True)
def writeMulti(image_list, file_name=None, dir=None, hdu_list=None, add_wcs=True, clobber=True, compression='auto'): """Write a Python list of images to a multi-extension FITS file. The details of how the images are written to file depends on the arguments. @param image_list A Python list of Images. @param file_name The name of the file to write to. Either `file_name` or `hdu_list` is required. @param dir Optionally a directory name can be provided if the file_name does not already include it. @param hdu_list A pyfits HDUList. If this is provided instead of file_name, then the image is appended to the end of the HDUList as a new HDU. In that case, the user is responsible for calling either hdu_list.writeto(...) or galsim.fits.writeFile(...) afterwards. Either `file_name` or `hdu_list` is required. @param add_wcs See documentation for this parameter on the galsim.fits.write method. @param clobber See documentation for this parameter on the galsim.fits.write method. @param compression See documentation for this parameter on the galsim.fits.write method. """ import pyfits # put this at function scope to keep pyfits optional file_compress, pyfits_compress = _parse_compression(compression, file_name) if file_name and hdu_list is not None: raise TypeError( "Cannot provide both file_name and hdu_list to write()") if not (file_name or hdu_list is not None): raise TypeError("Must provide either file_name or hdu_list to write()") if hdu_list is None: hdu_list = pyfits.HDUList() for image in image_list: hdu = _add_hdu(hdu_list, image.array, pyfits_compress) _write_header(hdu, add_wcs, image.scale, image.xmin, image.ymin) if file_name: if dir: import os file_name = os.path.join(dir, file_name) _write_file(file_name, hdu_list, clobber, file_compress, pyfits_compress)
def save_PDF_sparse(zfine, pdfs, head, Pars, path='', filebase='', num=-1, oob='no', var='', multiple='no', rank=0): """ Saves photo-z PDFs in sparse representation """ if path == '': path = Pars.path_results if not os.path.exists(path): os.system('mkdir -p ' + path) if filebase == '': filebase = Pars.finalfilename if num == -1: for j in range(100): if os.path.exists(path + filebase + '.' + str(j) + '.mlz') and os.path.exists(path + filebase + '.' + str(j) + '.P.npy'): continue else: fileoutPDF = path + filebase + '.' + str(j) + '.Psparse' if oob == 'yes': fileoutPDF = path + filebase + '_oob' + var + '.' + str( j) + '.P' break else: fileoutPDF = path + filebase + '.' + str(num) + '.Psparse' if oob == 'yes': fileoutPDF = path + filebase + '_oob' + var + '.' + str(num) + '.P' if multiple == 'yes': fileoutPDF = fileoutPDF + '_' + str(rank) col1 = pf.Column(name='redshift', format='E', array=zfine) fmt = '%dJ' % head['N_SPARSE'] col2 = pf.Column(name='Sparse_indices', format=fmt, array=pdfs) table1 = pf.BinTableHDU.from_columns(pf.ColDefs([col1])) table2 = pf.BinTableHDU.from_columns(pf.ColDefs([col2])) prihdu = pf.PrimaryHDU(header=head) hdulist = pf.HDUList([prihdu, table1, table2]) hdulist.writeto(fileoutPDF + '.fits', clobber=True)
def writefits(array, filename): import numpy import pyfits, os # Writes fits files of a given array newfits = pyfits.HDUList() hdu = pyfits.PrimaryHDU() hdu.data = array newfits.append(hdu) # Remove old version of file before if os.path.isfile(filename): os.remove(filename) newfits.writeto(filename) newfits.close return
def ppsave(pp, outroot="logs/out"): """ Produces output files for a ppxf object. """ arrays = ["matrix", "w", "bestfit", "goodpixels", "galaxy", "noise"] delattr(pp, "star_rfft") delattr(pp, "star") hdus = [] for i, att in enumerate(arrays): if i == 0: hdus.append(pf.PrimaryHDU(getattr(pp, att))) else: hdus.append(pf.ImageHDU(getattr(pp, att))) delattr(pp, att) hdulist = pf.HDUList(hdus) hdulist.writeto(outroot + ".fits", clobber=True) with open(outroot + ".pkl", "w") as f: pickle.dump(pp, f)
def make_fits_model(filename,array,delta,rpix): os.system('rm ' + filename) hdu = pyfits.PrimaryHDU(array) hdulist = pyfits.HDUList([hdu]) # setup the output fits file coordinate system. hdulist[0].header.append(('cdelt1', delta/3600.)) hdulist[0].header.append(('cdelt2', delta/3600.)) hdulist[0].header.append(('ctype1', 'RA---TAN')) hdulist[0].header.append(('ctype2', 'DEC--TAN')) hdulist[0].header.append(('crpix1', rpix)) hdulist[0].header.append(('crpix2', rpix)) hdulist[0].header.append(('crval1', 0)) hdulist[0].header.append(('crval2', 90.0)) hdulist.writeto(filename) return
def main(input_names, threshold, output_name): img = pyfits.open(input_names[0])[0].data mask = numpy.ones(img.shape, 'int') for input_name in input_names: print input_name img = pyfits.open(input_name)[0].data for i in range(0, img.shape[0]): for j in range(0, img.shape[1]): if img_utils.is_peak(img, i, j) and img[i, j] >= threshold: for k in img_utils.make_round_region(img, i, j, r): mask[k] = 0 print 'masked ratio=', (1 - float(scipy.sum(mask)) / img.size) * 100, '%' pyfits.HDUList(pyfits.PrimaryHDU(mask)).writeto(output_name, clobber=True)
def test_file_like(self): """ Tests the use of a file like object with no tell or seek methods in HDUList.writeto(), HDULIST.flush() or pyfits.writeto() """ hdu = fits.PrimaryHDU(np.arange(100, dtype=np.int32)) hdul = fits.HDUList() hdul.append(hdu) tmpfile = open(self.temp('tmpfile.fits'), 'wb') hdul.writeto(tmpfile) tmpfile.close() info = [(0, 'PRIMARY', 'PrimaryHDU', 5, (100,), 'int32', '')] assert fits.info(self.temp('tmpfile.fits'), output=False) == info
def _captureFits(shutterSpeed,filename,debayer): """ capture image to fits file @param shutterSpeed in microseconds @param filename where to store file. Existing file is overwritten @param debayer: If truem also return debayered image returns (raw,debayered) with debayer==None if debayer is False, else None """ with RawCamera() as camera: camera.shutter_speed=shutterSpeed raw,debayer=camera.capture(debayer) #print("camera: ISO=",camera.iso, ", analogGain=",camera.analog_gain, "awb_gains=",camera.awb_gains) hdu=pyfits.PrimaryHDU(raw) # FIXME add some fits keywords, such as date hduList=pyfits.HDUList([hdu]) hdu.writeto(filename,clobber=True) return (raw,debayer)
def makeBias(self, combine='median', biaslist=[], output='zeroim.fits'): ''' Combines the bias frames to a single bias frame. note: that this does not do sigma clipping at the moment :param: combine, either median or mean :param: biaslist, a list of bias frames to be combined :param: output: the name of the output file :return: combined bias frame :rtype: ndarray ''' self.masterBias = output #if no biaslist is given then assuming that all files should be used if len(biaslist) == 0: biaslist = self.biasFiles if self.dataWeird: filedata = [ pf.getdata(x, ignore_missing_end=True)[0] for x in biaslist ] else: filedata = [ pf.getdata(x, ignore_missing_end=True) for x in biaslist ] if len(set(x.shape for x in filedata)) > 1: self.log.info( 'BIAS images are not of same size! Program will exit..') sys.exit('BIAS images are not of same size! Program will exit..') #calculates the median of all biases #self.bias = numpy.median(filedata, axis=0) cmd = 'np.' + combine + '(filedata, axis=0)' self.bias = eval(cmd) self.log.info('Bias frames combined with {0:>s}'.format(cmd)) #write the output hdu = pf.PrimaryHDU(self.bias) hdulist = pf.HDUList([hdu]) hdulist.writeto(self.masterBias) self.log.info('Master bias saved to {0:>s}'.format(self.masterBias)) return self.bias
def run_corr2(x, y, g1, g2, min_sep=0.1, max_sep=10., nbins=8, temp_cat='temp.cat', params_file='corr2.params', m2_file_name='temp.m2', xy_units='degrees', sep_units='degrees', corr2_exec='corr2'): """Run Mike Jarvis' corr2 correlation function code using FITS files for the I/O. """ import os import subprocess import tempfile import pyfits # Create temporary, unique files for I/O catfile = tempfile.mktemp(suffix=temp_cat) m2file = tempfile.mktemp(suffix=m2_file_name) # Use fits binary table for faster I/O. (Converting to/from strings is slow.) assert x.shape == y.shape assert x.shape == g1.shape assert x.shape == g2.shape x_col = pyfits.Column(name='x', format='1D', array=x.flatten()) y_col = pyfits.Column(name='y', format='1D', array=y.flatten()) g1_col = pyfits.Column(name='g1', format='1D', array=g1.flatten()) g2_col = pyfits.Column(name='g2', format='1D', array=g2.flatten()) cols = pyfits.ColDefs([x_col, y_col, g1_col, g2_col]) table = pyfits.new_table(cols) phdu = pyfits.PrimaryHDU() hdus = pyfits.HDUList([phdu, table]) hdus.writeto(catfile, clobber=True) subprocess.Popen([ corr2_exec, params_file, 'file_name=' + str(catfile), 'm2_file_name=' + str(m2file), 'file_type=FITS', 'min_sep=%f' % min_sep, 'max_sep=%f' % max_sep, 'nbins=%f' % nbins, 'x_units=' + str(xy_units), 'y_units=' + str(xy_units), 'sep_units=' + str(sep_units) ]).wait() results = np.loadtxt(m2file) os.remove(catfile) os.remove(m2file) return results
def writeMatchListAsFits(matchList, fileName, log=NoLogging()): """ write matchList to a given filename with pyfits. """ if matchList != None and len(matchList) > 0: nSource = len(matchList) outputs = getMatchOutputList() nOut = len(outputs) log.log(log.DEBUG, "Writing %d matches" % nOut) # create the arrays and fill them arrays = {} for i in range(nOut): columnName = outputs[i]["label"] arrays[columnName] = numpy.zeros(nSource, dtype=outputs[i]["dtype"]) for i in range(nOut): columnName = outputs[i]["label"] isangle = outputs[i]['angle'] for j, sourceMatch in enumerate(matchList): s1 = sourceMatch.first s2 = sourceMatch.second if outputs[i]['side'] == 1: s = s1 # catalog else: s = s2 # source getMethod = getattr(s, outputs[i]["get"]) X = getMethod() if isangle: arrays[columnName][j] = X.asDegrees() else: arrays[columnName][j] = X # create the column defs columnDefs = [] for i in range(nOut): columnName = outputs[i]["label"] columnDefs.append( pyfits.Column(name=columnName, format=outputs[i]["fitstype"], unit=outputs[i]['units'], array=arrays[columnName])) tabhdu = pyfits.new_table(columnDefs, nrows=nSource) hdulist = pyfits.HDUList([pyfits.PrimaryHDU(), tabhdu]) hdulist.writeto(fileName, clobber=True)
def sumimages(files): imsum = 0 #for filename in files: for i in range(len(files)): print i, files[i] fitsobj = pyfits.open(files[i]) imsum = imsum + fitsobj[0].data outim = pyfits.HDUList() outhdu = pyfits.PrimaryHDU() outhdu.data = imsum outim.append(outhdu) # outim.writeto('total.fits') try: outim.writeto('total.fits') except: os.system('rm total.fits') outim.writeto('total.fits')
def mergefitsfiles(outfitsname, filelist, name_it): """ mergefitsfiles(outfitsname, filelist) """ fitsout=pyfits.HDUList() count = 0 for filename in filelist: new_names= name_it[count] fitsin=pyfits.open(filename) fitsimage=pyfits.ImageHDU(fitsin[0].data, fitsin[0].header, name=new_names) fitsout.append(fitsimage) count = count + 1 if (os.path.exists(outfitsname)): os.remove(outfitsname) fitsout.verify(option='silentfix') fitsout.writeto(outfitsname) return 1
def im2rgbfits(infile, rgbfile='', overwrite=False, headerfile=None, flip=False): if rgbfile == '': rgbfile = decapfile(infile) + '_RGB.fits' if exists(rgbfile): if overwrite: delfile(rgbfile) else: print rgbfile, 'EXISTS' sys.exit(1) #im = Image.open(infile) #print 'Loading data...' #data = array(im.getdata()) #nxc, nyc = im.size #data.shape = (nyc,nxc,3) #data = transpose(data, (2,0,1)) data = loadrgb(infile) #hdu = pyfits.PrimaryHDU() header = headerfile and pyfits.getheader(headerfile) hdu = pyfits.PrimaryHDU(None, header) hdulist = pyfits.HDUList([hdu]) hdulist.writeto(rgbfile) try: # If there's a 'SCI' extension, then that's where the WCS is header = pyfits.getheader(headerfile, 'SCI') except: pass if header <> None: if 'EXTNAME' in header.keys(): del (header['EXTNAME']) for i in range(3): print 'RGB'[i] data1 = data[i] if flip: data1 = flipud(data1) pyfits.append(rgbfile, data1, header) print rgbfile, 'NOW READY FOR "Open RGB Fits Image" in ds9'
def write_extract_fits(ofile, ap_list, clobber=False): """Write out the extracted spectrum to a FITS table. If the file already exists, this will not overwrite it. For each spectrum in ap_list, it will add another extension to the fits file. Each extension will have the first column as wavelength, the second column as counts, and the third column as sigma on the counts. ofile: Output file to write ap_list: List of extracted spectrum clobber: delete ofile if it already exists """ # delete the file if os.path.isfile(ofile) and clobber: saltio.delete(ofile) # create the primary array hdu = pyfits.PrimaryHDU() hdulist = pyfits.HDUList([hdu]) # create the columns and the for ap in ap_list: fvar = abs(ap.lvar)**0.5 # create the columns col1 = pyfits.Column(name='wavelength', format='D', unit='Angstroms', array=ap.wave) col2 = pyfits.Column(name='counts', format='D', unit='Counts', array=ap.ldata) col3 = pyfits.Column(name='counts_err', format='D', array=fvar) # add to the table tbhdu = pyfits.new_table([col1, col2, col3]) hdulist.append(tbhdu) # write it out hdulist.writeto(ofile) return
def average_header_fits(folder, input_header, output_file): fitslist = sort(glob.glob(folder + "*.fits")) headermatch = [] for fits in fitslist: if pyfits.getheader(fits)["OBJECT"] == input_header: print fits headermatch.append(pyfits.getdata(fits)) headermatch = array(headermatch) headermatch = average(headermatch, axis=0) hdu = pyfits.PrimaryHDU(headermatch) hdulist = pyfits.HDUList([hdu]) hdulist.writeto(output_file) return headermatch
def main(names): baseNames = [] for name in names: if name.endswith(suffix % "img"): baseNames.append(name[0:len(name) - len(suffix % "img")]) elif not name.endswith("fits") and os.path.exists(name + suffix % "img"): baseNames.append(name) for baseName in baseNames: imgName = baseName + suffix % "img" mskName = baseName + suffix % "msk" varName = baseName + suffix % "var" miName = baseName + ".fits" if os.path.exists(imgName) and os.path.exists( mskName) and os.path.exists(varName): print "Converting '%s_(img|mask|var).fits' to '%s.fits'" % ( baseName, baseName) imgFits = pyfits.open(imgName, do_not_scale_image_data=True) mskFits = pyfits.open(mskName, do_not_scale_image_data=True) varFits = pyfits.open(varName, do_not_scale_image_data=True) assert (len(imgFits) == 1) assert (len(mskFits) == 1) assert (len(varFits) == 1) imgHdu = pyfits.ImageHDU(data=imgFits[0].data, header=imgFits[0].header) imgHdu.header["EXTTYPE"] = "IMAGE" mskHdu = pyfits.ImageHDU(data=mskFits[0].data, header=mskFits[0].header) mskHdu.header["EXTTYPE"] = "MASK" varHdu = pyfits.ImageHDU(data=varFits[0].data, header=varFits[0].header) varHdu.header["EXTTYPE"] = "VARIANCE" miFits = pyfits.HDUList( [pyfits.PrimaryHDU(), imgHdu, mskHdu, varHdu]) if os.path.exists(miName): os.remove(miName) miFits.writeto(miName) imgFits.close() mskFits.close() varFits.close() os.remove(imgName) os.remove(mskName) os.remove(varName) else: print "Images with base name '%s' not found; skipping." % baseName
def remove_stray_light_raw(input_file, output_file): hdu = pyfits.open(input_file) hdu_out = [None] * 25 hdu_out[0] = pyfits.PrimaryHDU(hdu[0].data) hdu_out[0].header = hdu[0].header for i in range(1, 25): img = hdu[i].data hdr = hdu[i].header print img.shape bias1 = numpy.median(img[22:2119, 1:31].flatten()) bias2 = numpy.median(img[2152:4204, 1:31].flatten()) bias3 = numpy.median(img[22:2119, 4192:-1].flatten()) bias4 = numpy.median(img[2120:4204, 4192:-1].flatten()) print bias1, bias2, bias3, bias4 stray1 = numpy.median( ndimage.filters.gaussian_filter1d(img[32:2087, 32:39] - bias1, 5, axis=0), 1) stray2 = numpy.median( ndimage.filters.gaussian_filter1d(img[2151:4207, 32:39] - bias2, 5, axis=0), 1) stray3 = numpy.median( ndimage.filters.gaussian_filter1d(img[32:2087, 4183:4190] - bias3, 5, axis=0), 1) stray4 = numpy.median( ndimage.filters.gaussian_filter1d(img[2151:4207, 4183:4190] - bias4, 5, axis=0), 1) img[32:2087, 32:2079] = img[32:2087, 32:2079] - stray1[:, numpy.newaxis] img[2151:4207, 32:2079] = img[2151:4207, 32:2079] - stray2[:, numpy.newaxis] img[32:2087, 2144:4191] = img[32:2087, 2144:4191] - stray3[:, numpy.newaxis] img[2151:4207, 2144:4191] = img[2151:4207, 2144:4191] - stray4[:, numpy.newaxis] hdu_out[i] = pyfits.ImageHDU(img) hdu_out[i].header = hdu[i].header hdu = pyfits.HDUList(hdu_out) hdu.writeto(output_file, clobber=True)