def aligntocat(cube,catalogue): """ Take a cube and compare the sources in the field to the positions in the reference catalogue. Return offsets in ra/dec that can be used for re-projecting the cube This makes use of pyguide to find stars and centroid on them """ import PyGuide import numpy as np from astropy import wcs print("Processing cube {} for offsets".format(cube)) #first project the cube to create a white image with wcs img, var, wcsimg = cube2img(cube) #load the reference stars starcat=np.loadtxt(catalogue,dtype={'names': ('ra','dec'),'formats': ('f4', 'f4')}) #loop on reference stars and centroid nref=len(starcat['ra']) #space for offsets raoffcurrent=[] decoffcurrent=[] for sr in range(nref): #find first guess pix = wcsimg.wcs_world2pix(starcat['ra'][sr],starcat['dec'][sr],0) #centroid within 20 pixels ccd=PyGuide.CCDInfo(0,0,1) #handle weird errors for bas pixels usethis=True try: centroid=PyGuide.centroid(img,None,None,[pix[0],pix[1]],20,ccd) except: usethis=False #back to ra/dec if centroid is good if ((centroid.isOK) & (usethis)): coord = wcsimg.wcs_pix2world(centroid.xyCtr[0],centroid.xyCtr[1],0) raoffcurrent.append(coord[0]-starcat['ra'][sr]) decoffcurrent.append(coord[1]-starcat['dec'][sr]) #stack offsets raoff=np.median(np.array(raoffcurrent)) decoff=np.median(np.array(decoffcurrent)) print("Offsets for cube {} RA: {} Dec: {}".format(cube,raoff*3600.,decoff*3600.)) print("Error offsets for cube {} RA: {} Dec: {}".format(cube,np.std(np.array(raoffcurrent))*3600., np.std(np.array(decoffcurrent))*3600.)) return raoff,decoff
def doFindStars(imName=None, maskName=None, satMaskName=None, invertMask=False, **kargs): """Find stars and centroid and shape-fit them. Inputs: - all the arguments for loadFiles plus values shown by showDef """ global isSat, sd im, mask, satMask = loadFiles(imName, maskName, satMaskName, invertMask) # check keyword arguments for paramName in kargs: if paramName not in FindParamNames: raise RuntimeError("Invalid argument: %s" % (paramName, )) # fill in defaults globalDict = globals() for paramName in FindParamNames: if paramName not in kargs: kargs[paramName] = globalDict[paramName] # split off ccd info ccdInfoDict = {} for paramName in CCDInfoNames: ccdInfoDict[paramName] = kargs.pop(paramName) ccdInfo = PyGuide.CCDInfo(**ccdInfoDict) # find stars and centroid print("Calling PyGuide.findStars") ctrDataList, imStats = PyGuide.findStars(data=im, mask=mask, satMask=satMask, ccdInfo=ccdInfo, **kargs) print("%s stars found:" % (len(ctrDataList), )) printStarHeader() for ctrData in ctrDataList: # measure star shape try: shapeData = PyGuide.starShape( data=im, mask=mask, xyCtr=ctrData.xyCtr, rad=ctrData.rad, ) except RuntimeError as e: print("starShape failed: %s" % (e, )) shapeData = PyGuide.StarShapeData() printStarData(ctrData, shapeData)
def centeredcentroids(data, mask=None): """Finds centroids in an image, with (0,0) at the center of the image Parameters: data (ndarray): a 2d numpy array containing image data, assumed to be x row major mask (ndarray): a 2d numpy array containing binary image data (0 for do process and 1 for don't) Returns: xys (list): a list of interleaved xy positions these are the positions of the centroids in the image """ centroids, stats = PyGuide.findStars(data, mask, None, PyGuide.CCDInfo(2176, 19, 2.1), thresh=10, radMult=1.0, rad=None, verbosity=0, doDS9=False) out = [] for centroid in centroids: out.append(centroid.xyCtr[0]-data.shape[1]/2) out.append(centroid.xyCtr[1]-data.shape[0]/2) return out
def unitdiskcentroids(data, mask=None): """Finds centroids in an image, with (0,0) at the center of the image and the largest possible circle around this (0,0) having magnitude 1 Parameters: data (ndarray): a 2d numpy array containing image data, assumed to be x row major mask (ndarray): a 2d numpy array containing binary image data (0 for do process and 1 for don't) Returns: xys (list): a list of interleaved xy positions these are the positions of the centroids in the image """ centroids, stats = PyGuide.findStars(data, mask, None, PyGuide.CCDInfo(2176, 19, 2.1), thresh=10, radMult=1.0, rad=None, verbosity=0, doDS9=False) out = [] scale = min(data.shape[0],data.shape[1])/2 for centroid in centroids: out.append((centroid.xyCtr[0]-data.shape[1]/2)/scale) out.append((centroid.xyCtr[1]-data.shape[0]/2)/scale) return out
def presskey(self, event): """ Do stuff when press key """ #quit on q if (event.key == "q"): self.OnExit() #centroid on c elif (event.key == "c"): ccd = PyGuide.CCDInfo(0, 0, 1) centroid = PyGuide.centroid(self.fitimg, None, None, [event.xdata, event.ydata], 20, ccd) self.starx.append(centroid.xyCtr[0]) self.stary.append(centroid.xyCtr[1]) thisra, thisdec = self.wcs.wcs_pix2world( centroid.xyCtr[0], centroid.xyCtr[1], 1) self.starra.append(thisra) self.stardec.append(thisdec) self.starid.append(self.find_id(thisra, thisdec)) self.nstars = self.nstars + 1 self.update_twodimage(update=True) #store bottom left corner on L elif (event.key == "n"): try: check = float(event.xdata) + float(event.ydata) self.boxlx.append(event.xdata) self.boxly.append(event.ydata) self.warning.set("STATUS: Now mark top/right corner!") except: self.boxlx.append(event.xdata) self.boxly.append(event.ydata) self.warning.set( "STATUS: Missed data region... try again!") elif (event.key == "m"): try: check = float(event.xdata) + float(event.ydata) self.boxrx.append(event.xdata) self.boxry.append(event.ydata) self.nbox = self.nbox + 1 self.update_twodimage(update=True) self.warning.set("STATUS: All good!") except: self.warning.set( "STATUS: Missed data region... try again!") elif (event.key == "d"): if (self.nbox > 0): self.boxlx = self.boxlx[0:-1] self.boxly = self.boxly[0:-1] self.boxrx = self.boxrx[0:-1] self.boxry = self.boxry[0:-1] self.nbox = self.nbox - 1 if (self.nstars > 0): self.starra = self.starra[0:-1] self.stardec = self.stardec[0:-1] self.starid = self.starid[0:-1] self.starx = self.starx[0:-1] self.stary = self.stary[0:-1] self.nstars = self.nstars - 1 self.update_twodimage(update=True)
import calendar import time import timeit import cv2 DEBUG = True #add path to PyGuide, I think it is some weirdness going on with using #Anaconda and what paths are set. sys.path.append("/usr/local/lib/python2.7/dist-packages") import PyGuide # Default Parameters # these settings will need to be updated once we have the real guide camera # in order, bias (ADU), readnoise (e-), gain (e-/ADU), saturation level (ADU) ccdInfo = PyGuide.CCDInfo(10.0, 4.01, 1.5, 256) # these are general settings thresh = 5.0 radMult = 3.0 rad = 20 satLevel = (2**8) - 1 verbosity = 0 doDS9 = False mask = None satMask = None def imageList(fpath): """Find all images with a given extention and return their names as a list""" flist = raw_input("What is the file identifier? (*.?) >")
2005-10-14 ROwen Supply null satMask for PyGuide 2.1. 2008-01-02 ROwen Added DoSmooth constant. 2009-11-20 ROwen Modified to use numpy. """ import numpy import PyGuide from Stats import Stats # settings DoSmooth = True ImWidth = 64 Sky = 1000, # sky level, in ADU CCDInfo = PyGuide.CCDInfo( bias=2176, # image bias, in ADU readNoise=19, # read noise, in e- ccdGain=2.1, # inverse ccd gain, in e-/ADU ) Thresh = 2.5 imShape = (ImWidth, ImWidth) nomCtr = (ImWidth // 2, ImWidth // 2) mask = numpy.zeros(imShape, numpy.bool) NaN = float("NaN") # settings AmplValues = (100, 1000, 10000) FWHMValues = (2.0, 3.0, 4.0) MaskWidthsPerFWHM = (0.0, 0.5, 1.0, 1.5, 2.0) # fractions of a FWHM NumTries = 20
#filePath = input("Enter path to file (eg. ~/Pictures/SX_CCD): ") #dataFile = input("Enter desired output file (eg. data.csv): ") if filePath[0] == '~': filePath = os.path.expanduser('~') + filePath[1:] if dataFile[0] == '~': dataFile = os.path.expanduser('~') + dataFile[1:] #print(filePath) #print(dataFile) CCDInfo = PyGuide.CCDInfo( bias=BIAS_LEVEL, # image bias, in ADU readNoise=READ_NOISE, # read noise, in e- ccdGain=GAIN, # inverse ccd gain, in e-/ADU ) if filePath[len(filePath) - 5:] == '.fits': dataListTemp = single_image(filePath) dataList = [] dataList.append(dataListTemp) write_to_csv(dataFile, dataList) else: if filePath[len(filePath) - 1] != '/': filePath = filePath + '/' if not os.path.exists(filePath): print("ERROR: That file path does not exist.")
2004-08-04 ROwen Modified to work with 2004-08-03 findStars. 2004-08-06 ROwen Modified to work with 2004-08-06 findStars. 2005-02-07 ROwen Modified for PyGuide 1.2. Modified to show shape info for all found stars. 2005-04-19 ROwen Modified for PyGuide 2.0 2005-10-14 ROwen Supply null satMask for PyGuide 2.1. """ import os.path import sys import PyGuide import pyfits # these values are probably wrong for the given test image CCDInfo = PyGuide.CCDInfo( bias=200, # image bias, in ADU readNoise=21.391, # read noise, in e- ccdGain=1.643, # ccd gain, in e-/pixel ) UseDS9 = True if len(sys.argv) > 1: filename = sys.argv[1] else: testDir = os.path.dirname(__file__) filename = os.path.join(testDir, "test.fits") testimg = pyfits.open(filename) data = testimg[0].data if UseDS9:
def doCentroid(imName=None, maskName=None, satMaskName=None, xyGuess=None, invertMask=False, **kargs): """Centroid and shape-fit a star Inputs: - all the arguments for loadFiles plus most values shown by showDef """ global im, imFits, mask, maskFits, satMask, satMaskFits, isSat, sd im, mask, satMask = loadFiles(imName, maskName, satMaskName, invertMask) if xyGuess is None: print("xyGuess is required") return # check keyword arguments for paramName in kargs: if paramName not in CentroidParamNames: raise RuntimeError("Invalid argument: %s" % (paramName, )) # fill in defaults globalDict = globals() for paramName in CentroidParamNames: if paramName not in kargs: kargs[paramName] = globalDict[paramName] # split off ccd info ccdInfoDict = {} for paramName in CCDInfoNames: ccdInfoDict[paramName] = kargs.pop(paramName) ccdInfo = PyGuide.CCDInfo(**ccdInfoDict) if kargs["rad"] is None: print("rad argument is required because the default is presently None") return verbosity = kargs["verbosity"] # centroid ctrData = PyGuide.centroid(data=im, mask=mask, satMask=satMask, xyGuess=xyGuess, ccdInfo=ccdInfo, **kargs) if not ctrData.isOK: print("centroid failed:", ctrData.msgStr) return shapeData = PyGuide.starShape( data=im, mask=mask, xyCtr=ctrData.xyCtr, rad=ctrData.rad, verbosity=verbosity, ) # print results printStarHeader() printStarData(ctrData, shapeData) if not shapeData.isOK: print("starShape failed:", shapeData.msgStr)