def runFilter(infile, outfile, filterStrength): from mroipac.filter.Filter import Filter logger.info("Applying power-spectral filter") # Initialize the flattened interferogram topoflatIntFilename = infile intImage = isceobj.createIntImage() intImage.load(infile + '.xml') intImage.setAccessMode('read') intImage.createImage() # Create the filtered interferogram filtImage = isceobj.createIntImage() filtImage.setFilename(outfile) filtImage.setWidth(intImage.getWidth()) filtImage.setAccessMode('write') filtImage.createImage() objFilter = Filter() objFilter.wireInputPort(name='interferogram', object=intImage) objFilter.wireOutputPort(name='filtered interferogram', object=filtImage) objFilter.goldsteinWerner(alpha=filterStrength) intImage.finalizeImage() filtImage.finalizeImage()
def runFilterG(infile, outfile, filterStrength): # Initialize the flattened interferogram intImage = isceobj.createIntImage() intImage.load(infile + '.xml') intImage.setAccessMode('read') intImage.createImage() # Create the filtered interferogram filtImage = isceobj.createIntImage() filtImage.setFilename(outfile) filtImage.setWidth(intImage.getWidth()) filtImage.setLength(intImage.getLength()) filtImage.setAccessMode('write') filtImage.createImage() img = intImage.memMap(mode='r', band=0) original = np.fft.fft2(img[:, :]) center = np.fft.fftshift(original) LowPassCenter = center * gaussianLP(100, img.shape) LowPass = np.fft.ifftshift(LowPassCenter) inverse_LowPass = np.fft.ifft2(LowPass) out_filtered = filtImage.asMemMap(outfile) out_filtered[:, :, 0] = inverse_LowPass[:, :] filtImage.renderHdr() intImage.finalizeImage() filtImage.finalizeImage()
def runFilter_gaussian(infile, outfile, filterStrength): from isceobj import Filter logger.info("Applying power-spectral filter") # Initialize the flattened interferogram topoflatIntFilename = infile intImage = isceobj.createIntImage() intImage.load(infile + '.xml') intImage.setAccessMode('read') intImage.createImage() # Create the filtered interferogram filtImage = isceobj.createIntImage() filtImage.setFilename(outfile) filtImage.setWidth(intImage.getWidth()) filtImage.setAccessMode('write') filtImage.createImage() objFilter = Filter() objFilter.wireInputPort(name='interferogram', object=intImage) objFilter.wireOutputPort(name='filtered interferogram', object=filtImage) objFilter.gaussianFilter(filterWidth=10, filterHeight=10, sigma=1) intImage.finalizeImage() filtImage.finalizeImage()
def filter_ifg(ifgFilename, outname=None, filterStrength=0.5): ifgDirname = os.path.dirname(ifgFilename) filename_only = os.path.split(ifgFilename)[1] if outname is None: outname = os.path.join(ifgDirname, "filt_" + filename_only) img1 = isceobj.createImage() img1.load(ifgFilename + ".xml") widthInt = img1.getWidth() intImage = isceobj.createIntImage() intImage.setFilename(ifgFilename) intImage.setWidth(widthInt) intImage.setAccessMode("read") intImage.createImage() # Create the filtered interferogram filtImage = isceobj.createIntImage() filtImage.setFilename(outname) filtImage.setWidth(widthInt) filtImage.setAccessMode("write") filtImage.createImage() objFilter = Filter() objFilter.wireInputPort(name="interferogram", object=intImage) objFilter.wireOutputPort(name="filtered interferogram", object=filtImage) objFilter.goldsteinWerner(alpha=filterStrength) intImage.finalizeImage() filtImage.finalizeImage()
def generateIgram(imageSlc1, imageSlc2, resampName, azLooks, rgLooks): objSlc1 = isceobj.createSlcImage() IU.copyAttributes(imageSlc1, objSlc1) objSlc1.setAccessMode('read') objSlc1.createImage() objSlc2 = isceobj.createSlcImage() IU.copyAttributes(imageSlc2, objSlc2) objSlc2.setAccessMode('read') objSlc2.createImage() slcWidth = imageSlc1.getWidth() intWidth = int(slcWidth / rgLooks) lines = min(imageSlc1.getLength(), imageSlc2.getLength()) if '.flat' in resampName: resampAmp = resampName.replace('.flat', '.amp') elif '.int' in resampName: resampAmp = resampName.replace('.int', '.amp') else: resampAmp += '.amp' resampInt = resampName objInt = isceobj.createIntImage() objInt.setFilename(resampInt) objInt.setWidth(intWidth) imageInt = isceobj.createIntImage() IU.copyAttributes(objInt, imageInt) objInt.setAccessMode('write') objInt.createImage() objAmp = isceobj.createAmpImage() objAmp.setFilename(resampAmp) objAmp.setWidth(intWidth) imageAmp = isceobj.createAmpImage() IU.copyAttributes(objAmp, imageAmp) objAmp.setAccessMode('write') objAmp.createImage() objCrossmul = crossmul.createcrossmul() objCrossmul.width = slcWidth objCrossmul.length = lines objCrossmul.LooksDown = azLooks objCrossmul.LooksAcross = rgLooks objCrossmul.crossmul(objSlc1, objSlc2, objInt, objAmp) for obj in [objInt, objAmp, objSlc1, objSlc2]: obj.finalizeImage() return imageInt, imageAmp
def run(imageSlc1, imageSlc2, resampName, azLooks, rgLooks): objSlc1 = isceobj.createSlcImage() #right now imageSlc1 and 2 are just text files, need to open them as image IU.copyAttributes(imageSlc1, objSlc1) objSlc1.setAccessMode('read') objSlc1.createImage() objSlc2 = isceobj.createSlcImage() IU.copyAttributes(imageSlc2, objSlc2) objSlc2.setAccessMode('read') objSlc2.createImage() slcWidth = imageSlc1.getWidth() intWidth = int(slcWidth / rgLooks) lines = min(imageSlc1.getLength(), imageSlc2.getLength()) resampAmp = resampName + '.amp' resampInt = resampName + '.int' objInt = isceobj.createIntImage() objInt.setFilename(resampInt) objInt.setWidth(intWidth) imageInt = isceobj.createIntImage() IU.copyAttributes(objInt, imageInt) objInt.setAccessMode('write') objInt.createImage() objAmp = isceobj.createAmpImage() objAmp.setFilename(resampAmp) objAmp.setWidth(intWidth) imageAmp = isceobj.createAmpImage() IU.copyAttributes(objAmp, imageAmp) objAmp.setAccessMode('write') objAmp.createImage() objCrossmul = crossmul.createcrossmul() objCrossmul.width = slcWidth objCrossmul.length = lines objCrossmul.LooksDown = azLooks objCrossmul.LooksAcross = rgLooks objCrossmul.crossmul(objSlc1, objSlc2, objInt, objAmp) for obj in [objInt, objAmp, objSlc1, objSlc2]: obj.finalizeImage() return imageInt, imageAmp
def __init__(self, obj): basename = obj.insar.topophaseFlatFilename wrapName = basename unwrapName = basename.replace('.flat', '.unw') #Setup images self.ampImage = obj.insar.resampAmpImage.copy(access_mode='read') self.width = self.ampImage.getWidth() #intImage intImage = isceobj.createIntImage() intImage.initImage(wrapName, 'read', self.width) intImage.createImage() self.intImage = intImage #unwImage unwImage = isceobj.Image.createImage() unwImage.setFilename(unwrapName) unwImage.setWidth(self.width) unwImage.imageType = 'unw' unwImage.bands = 2 unwImage.scheme = 'BIL' unwImage.dataType = 'FLOAT' unwImage.setAccessMode('write') unwImage.createImage() self.unwImage = unwImage
def run(imageAmp, imageSim, prf, infos, stdWriter, catalog=None, sceneid='NO_ID'): logger.info("Running Rgoffset: %s" % sceneid) firstAc = infos['firstSampleAcross'] firstDown = infos['firstSampleDown'] numLocationAcross = infos['numberLocationAcross'] numLocationDown = infos['numberLocationDown'] objAmp = isceobj.createIntImage() IU.copyAttributes(imageAmp, objAmp) objAmp.setAccessMode('read') objAmp.createImage() widthAmp = objAmp.getWidth() intLength = objAmp.getLength() lastAc = widthAmp - firstAc lastDown = intLength - firstDown objSim = isceobj.createImage() IU.copyAttributes(imageSim, objSim) objSim.setAccessMode('read') objSim.createImage() objOffset = isceobj.createEstimateOffsets() objOffset.setSearchWindowSize(infos['offsetSearchWindowSize'], infos['sensorName']) objOffset.setFirstSampleAcross(firstAc) objOffset.setLastSampleAcross(lastAc) objOffset.setNumberLocationAcross(numLocationAcross) objOffset.setFirstSampleDown(firstDown) objOffset.setLastSampleDown(lastDown) objOffset.setNumberLocationDown(numLocationDown) #set the tag used in the outfile. each message is precided by this tag #if the writer is not of "file" type the call has no effect objOffset.stdWriter = stdWriter.set_file_tags("rgoffset", "log", "err", "out") objOffset.setFirstPRF(prf) objOffset.setSecondPRF(prf) objOffset.setAcrossGrossOffset(0) objOffset.setDownGrossOffset(0) objOffset.estimateoffsets(image1=objSim, image2=objAmp, band1=0, band2=0) if catalog is not None: # Record the inputs and outputs isceobj.Catalog.recordInputsAndOutputs(catalog, objOffset, "runRgoffset.%s" % sceneid, logger, "runRgoffset.%s" % sceneid) objAmp.finalizeImage() objSim.finalizeImage() return objOffset.getOffsetField()
def flattenWithOffsets(fname, offname, flatname, frame, rglooks): from isceobj.Util.ImageUtil import ImageLib as IML import logging ifg = IML.mmapFromISCE(fname, logging).bands[0] off = IML.mmapFromISCE(offname, logging).bands[0] lgt = min(ifg.shape[0], off.shape[0]) delr = 0.5 * SPEED_OF_LIGHT / frame.rangeSamplingRate wvl = frame.getInstrument().getRadarWavelength() factor = 4 * np.pi * delr * rglooks / wvl cJ = np.complex64(1.0j) fid = open(flatname, 'wb') for ii in range(lgt): data = ifg[ii] * np.exp(-cJ * factor * off[ii]) data.astype(np.complex64).tofile(fid) fid.close() img = isceobj.createIntImage() img.setFilename(flatname) img.setWidth(ifg.shape[1]) img.setAccessMode('READ') img.renderHdr() pass
def create_phsig(ifg_file, cor_file=None): from mroipac.icu.Icu import Icu logger.info("Estimating spatial coherence based phase sigma") if cor_file is None: ext = os.path.splitext(ifg_file)[1] cor_file = ifg_file.replace(ext, ".cor") logger.info("writing output to %s", cor_file) # Create phase sigma correlation file here intImage = isceobj.createIntImage() intImage.load(ifg_file.replace(".xml", "") + ".xml") intImage.setAccessMode("read") intImage.createImage() phsigImage = isceobj.createImage() phsigImage.dataType = "FLOAT" phsigImage.bands = 1 phsigImage.setWidth(intImage.getWidth()) phsigImage.setFilename(cor_file) phsigImage.setAccessMode("write") phsigImage.createImage() icuObj = Icu(name="filter_icu") icuObj.configure() icuObj.unwrappingFlag = False icuObj.useAmplitudeFlag = False icuObj.icu(intImage=intImage, phsigImage=phsigImage) phsigImage.renderHdr() intImage.finalizeImage() phsigImage.finalizeImage()
def create_xml(fileName, width, length, fileType): import isceobj if fileType == 'slc': image = isceobj.createSlcImage() elif fileType == 'int': image = isceobj.createIntImage() elif fileType == 'amp': image = isceobj.createAmpImage() elif fileType == 'cor': image = isceobj.createOffsetImage() elif fileType == 'rmg' or fileType == 'unw': image = isceobj.Image.createUnwImage() elif fileType == 'byte': image = isceobj.createImage() image.setDataType('BYTE') elif fileType == 'float': image = isceobj.createImage() image.setDataType('FLOAT') elif fileType == 'double': image = isceobj.createImage() image.setDataType('DOUBLE') else: raise Exception('format not supported yet!\n') image.setFilename(fileName) image.extraFilename = fileName + '.vrt' image.setWidth(width) image.setLength(length) #image.setAccessMode('read') #image.createImage() image.renderHdr()
def estCoherence(outfile, corfile): from mroipac.icu.Icu import Icu #Create phase sigma correlation file here filtImage = isceobj.createIntImage() filtImage.load(outfile + '.xml') filtImage.setAccessMode('read') filtImage.createImage() phsigImage = isceobj.createImage() phsigImage.dataType = 'FLOAT' phsigImage.bands = 1 phsigImage.setWidth(filtImage.getWidth()) phsigImage.setFilename(corfile) phsigImage.setAccessMode('write') phsigImage.createImage() icuObj = Icu(name='sentinel_filter_icu') icuObj.configure() icuObj.unwrappingFlag = False icuObj.useAmplitudeFlag = False #icuObj.correlationType = 'NOSLOPE' icuObj.icu(intImage=filtImage, phsigImage=phsigImage) phsigImage.renderHdr() filtImage.finalizeImage() phsigImage.finalizeImage()
def runUnwrap(self): '''Specific connector from an insarApp object to a Snaphu object.''' wrapName = self.insar.topophaseFlatFilename unwrapName = self.insar.unwrappedIntFilename #Setup images ampImage = self.insar.resampAmpImage.copy(access_mode='read') width = ampImage.getWidth() #intImage intImage = isceobj.createIntImage() intImage.initImage(wrapName, 'read', width) intImage.createImage() #unwImage unwImage = isceobj.Image.createUnwImage() unwImage.setFilename(unwrapName) unwImage.setWidth(width) unwImage.imageType = 'unw' unwImage.bands = 2 unwImage.scheme = 'BIL' unwImage.dataType = 'FLOAT' unwImage.setAccessMode('write') unwImage.createImage() icuObj = Icu(name='insarapp_icu') icuObj.configure() icuObj.icu(intImage=intImage, ampImage=ampImage, unwImage = unwImage) #At least one can query for the name used self.insar.connectedComponentsFilename = icuObj.conncompFilename ampImage.finalizeImage() intImage.finalizeImage() unwImage.finalizeImage() unwImage.renderHdr()
def run(method, ampImage, widthInt, infos, stdWriter, catalog=None, sceneid='NO_ID'): logger.info("Calculating Coherence: %s" % sceneid) # Initialize the flattened inteferogram topoflatIntFilename = infos['outputPath'] + '.' + infos['topophaseFlatFilename'] intImage = isceobj.createIntImage() intImage.setFilename(topoflatIntFilename) intImage.setWidth(widthInt) intImage.setAccessMode('read') intImage.createImage() # Create the coherence image cohFilename = topoflatIntFilename.replace('.flat', '.cor') cohImage = isceobj.createOffsetImage() cohImage.setFilename(cohFilename) cohImage.setWidth(widthInt) cohImage.setAccessMode('write') cohImage.createImage() cor = Correlation() cor.configure() cor.wireInputPort(name='interferogram', object=intImage) cor.wireInputPort(name='amplitude', object=ampImage) cor.wireOutputPort(name='correlation', object=cohImage) try: CORRELATION_METHOD[method](cor) except KeyError: print("Unrecognized correlation method") sys.exit(1) pass return None
def multiply(masname, slvname, outname, rngname, fact, masterFrame, flatten=True, alks=3, rlks=7, virtual=True): masImg = isceobj.createSlcImage() masImg.load( masname + '.xml') width = masImg.getWidth() length = masImg.getLength() if not virtual: master = np.memmap(masname, dtype=np.complex64, mode='r', shape=(length,width)) slave = np.memmap(slvname, dtype=np.complex64, mode='r', shape=(length, width)) else: master = loadVirtualArray(masname + '.vrt') slave = loadVirtualArray(slvname + '.vrt') if os.path.exists(rngname): rng2 = np.memmap(rngname, dtype=np.float32, mode='r', shape=(length,width)) else: print('No range offsets provided') rng2 = np.zeros((length,width)) cJ = np.complex64(-1j) #Zero out anytging outside the valid region: ifg = np.memmap(outname, dtype=np.complex64, mode='w+', shape=(length,width)) firstS = masterFrame.firstValidSample lastS = masterFrame.firstValidSample + masterFrame.numValidSamples -1 firstL = masterFrame.firstValidLine lastL = masterFrame.firstValidLine + masterFrame.numValidLines - 1 for kk in range(firstL,lastL + 1): ifg[kk,firstS:lastS + 1] = master[kk,firstS:lastS + 1] * np.conj(slave[kk,firstS:lastS + 1]) if flatten: phs = np.exp(cJ*fact*rng2[kk,firstS:lastS + 1]) ifg[kk,firstS:lastS + 1] *= phs #### master=None slave=None ifg = None objInt = isceobj.createIntImage() objInt.setFilename(outname) objInt.setWidth(width) objInt.setLength(length) objInt.setAccessMode('READ') objInt.renderHdr() try: outfile = takeLooks(objInt, alks, rlks) print('Output: ', outfile) except: raise Exception('Failed to multilook ifgs') return objInt
def coherence(amplitudeFile, interferogramFile, coherenceFile, method="cchz_wave", windowSize=5): ''' compute coherence using a window ''' import operator from mroipac.correlation.correlation import Correlation CORRELATION_METHOD = { 'phase_gradient': operator.methodcaller('calculateEffectiveCorrelation'), 'cchz_wave': operator.methodcaller('calculateCorrelation') } ampImage = isceobj.createAmpImage() ampImage.load(amplitudeFile + '.xml') ampImage.setAccessMode('read') ampImage.createImage() intImage = isceobj.createIntImage() intImage.load(interferogramFile + '.xml') intImage.setAccessMode('read') intImage.createImage() #there is no coherence image in the isceobj/Image cohImage = isceobj.createOffsetImage() cohImage.setFilename(coherenceFile) cohImage.setWidth(ampImage.width) cohImage.setAccessMode('write') cohImage.createImage() cor = Correlation() cor.configure() cor.wireInputPort(name='amplitude', object=ampImage) cor.wireInputPort(name='interferogram', object=intImage) cor.wireOutputPort(name='correlation', object=cohImage) cor.windowSize = windowSize cohImage.finalizeImage() intImage.finalizeImage() ampImage.finalizeImage() try: CORRELATION_METHOD[method](cor) except KeyError: print("Unrecognized correlation method") sys.exit(1) pass return None
def run_interferogram(inps, resampName): if inps.azlooks * inps.rglooks > 1: extention = '.ml.slc' else: extention = '.slc' with h5py.File(inps.stack_file, 'r') as ds: date_list = np.array([x.decode('UTF-8') for x in ds['date'][:]]) ref_ind = np.where(date_list==inps.reference)[0] sec_ind = np.where(date_list==inps.secondary)[0] phase_series = ds['phase'] amplitudes = ds['amplitude'] length = phase_series.shape[1] width = phase_series.shape[2] resampInt = resampName + '.int' intImage = isceobj.createIntImage() intImage.setFilename(resampInt) intImage.setAccessMode('write') intImage.setWidth(width) intImage.setLength(length) intImage.createImage() out_ifg = intImage.asMemMap(resampInt) box_size = 3000 num_row = int(np.ceil(length / box_size)) num_col = int(np.ceil(width / box_size)) for i in range(num_row): for k in range(num_col): row_1 = i * box_size row_2 = i * box_size + box_size col_1 = k * box_size col_2 = k * box_size + box_size if row_2 > length: row_2 = length if col_2 > width: col_2 = width ref_phase = phase_series[ref_ind, row_1:row_2, col_1:col_2].reshape(row_2 - row_1, col_2 - col_1) sec_phase = phase_series[sec_ind, row_1:row_2, col_1:col_2].reshape(row_2 - row_1, col_2 - col_1) ref_amplitude = amplitudes[ref_ind, row_1:row_2, col_1:col_2].reshape(row_2 - row_1, col_2 - col_1) sec_amplitude = amplitudes[sec_ind, row_1:row_2, col_1:col_2].reshape(row_2 - row_1, col_2 - col_1) ifg = (ref_amplitude * sec_amplitude) * np.exp(1j * (ref_phase - sec_phase)) out_ifg[row_1:row_2, col_1:col_2, 0] = ifg[:, :] intImage.renderHdr() intImage.finalizeImage() return length, width
def coherence(inps, method="phase_gradient"): #logger.info("Calculating Coherence") #get width from the header file of input interferogram width = getWidth(inps.intf + '.xml') # Initialize the amplitude ampImage = isceobj.createAmpImage() ampImage.setFilename(inps.amp) ampImage.setWidth(width) ampImage.setAccessMode('read') ampImage.createImage() #ampImage = self.insar.getResampOnlyAmp().copy(access_mode='read') # Initialize the flattened inteferogram intImage = isceobj.createIntImage() intImage.setFilename(inps.intf) intImage.setWidth(width) intImage.setAccessMode('read') intImage.createImage() # Create the coherence image #there is no coherence image in the isceobj/Image cohImage = isceobj.createOffsetImage() cohImage.setFilename(inps.cor) cohImage.setWidth(width) cohImage.setAccessMode('write') cohImage.createImage() cor = Correlation() cor.configure() cor.wireInputPort(name='interferogram', object=intImage) cor.wireInputPort(name='amplitude', object=ampImage) cor.wireOutputPort(name='correlation', object=cohImage) cor.windowSize = inps.winsize cohImage.finalizeImage() intImage.finalizeImage() ampImage.finalizeImage() try: CORRELATION_METHOD[method](cor) except KeyError: print("Unrecognized correlation method") sys.exit(1) pass return None
def get_isce_image(self,itype,fname,width,length): if itype == 'flat': im = isceobj.createIntImage() else: im = isceobj.createImage() im.dataType = 'FLOAT' if itype == 'unw': im.bands = 2 im.scheme = 'BIL' elif itype == 'ccomp': im.dataType = 'BYTE' im.filename = fname im.extraFilename = fname + '.vrt' im.width = width im.length = length return im
def runCoherence(self, method="phase_gradient"): logger.info("Calculating Coherence") # Initialize the amplitude # resampAmpImage = self.insar.resampAmpImage # ampImage = isceobj.createAmpImage() # IU.copyAttributes(resampAmpImage, ampImage) # ampImage.setAccessMode('read') # ampImage.createImage() #ampImage = self.insar.getResampOnlyAmp().copy(access_mode='read') # Initialize the flattened inteferogram topoflatIntFilename = self.insar.topophaseFlatFilename intImage = isceobj.createIntImage() #widthInt = self.insar.resampIntImage.getWidth() widthInt = self.insar.topophaseFlatFilename.getWidth() intImage.setFilename(topoflatIntFilename) intImage.setWidth(widthInt) intImage.setAccessMode('read') intImage.createImage() # Create the coherence image cohFilename = topoflatIntFilename.replace('.flat', '.cor') cohImage = isceobj.createOffsetImage() cohImage.setFilename(cohFilename) cohImage.setWidth(widthInt) cohImage.setAccessMode('write') cohImage.createImage() cor = Correlation() cor.configure() cor.wireInputPort(name='interferogram', object=intImage) #cor.wireInputPort(name='amplitude', object=ampImage) cor.wireOutputPort(name='correlation', object=cohImage) cohImage.finalizeImage() intImage.finalizeImage() #ampImage.finalizeImage() try: CORRELATION_METHOD[method](cor) except KeyError: print("Unrecognized correlation method") sys.exit(1) pass return None
def runCorrect(self): refScene = self._isce.refScene velocity, height = self._isce.vh() infos = {} for attribute in [ 'dopplerCentroid', 'peg', 'lookSide', 'numberRangeLooks', 'numberAzimuthLooks', 'topophaseMphFilename', 'topophaseFlatFilename', 'heightSchFilename', 'is_mocomp' ]: infos[attribute] = getattr(self._isce, attribute) infos['refOutputPath'] = os.path.join(self.getoutputdir(refScene), refScene) stdWriter = self._stdWriter refScene = self._isce.refScene refPol = self._isce.refPol refPair = self._isce.selectedPairs[0] #ML 2014-09-26 topoIntImage = self._isce.topoIntImages[refPair][refPol] for sceneid1, sceneid2 in self._isce.selectedPairs: pair = (sceneid1, sceneid2) objMocompbaseline = self._isce.mocompBaselines[pair] for pol in self._isce.selectedPols: frame1 = self._isce.frames[sceneid1][pol] objFormSLC1 = self._isce.formSLCs[sceneid1][pol] topoIntImage = self._isce.topoIntImages[pair][pol] #ML 2014-09-26 intImage = isceobj.createIntImage() IU.copyAttributes(topoIntImage, intImage) intImage.setAccessMode('read') sid = self._isce.formatname(pair, pol) infos['outputPath'] = os.path.join( self.getoutputdir(sceneid1, sceneid2), sid) catalog = isceobj.Catalog.createCatalog(self._isce.procDoc.name) run(frame1, objFormSLC1, objMocompbaseline, intImage, velocity, height, infos, stdWriter, catalog=catalog, sceneid=sid)
def runTopo(self): v, h = self._isce.vh() if self._isce.is_mocomp is None: self._isce.is_mocomp = self._isce.get_is_mocomp() infos = {} for attribute in [ 'dopplerCentroid', 'peg', 'demImage', 'numberRangeLooks', 'numberAzimuthLooks', 'topophaseIterations', 'is_mocomp', 'heightSchFilename', 'heightFilename', 'latFilename', 'lonFilename', 'losFilename', 'lookSide' ]: infos[attribute] = getattr(self._isce, attribute) stdWriter = self._stdWriter refScene = self._isce.refScene refPol = self._isce.refPol imgSlc1 = self._isce.slcImages[refScene][refPol] infos['intWidth'] = int(imgSlc1.getWidth() / infos['numberRangeLooks']) infos['intLength'] = int(imgSlc1.getLength() / infos['numberAzimuthLooks']) objFormSlc1 = self._isce.formSLCs[refScene][refPol] frame1 = self._isce.frames[refScene][refPol] infos['outputPath'] = os.path.join(self.getoutputdir(refScene), refScene) catalog = isceobj.Catalog.createCatalog(self._isce.procDoc.name) sid = self._isce.formatname(refScene) refPair = self._isce.selectedPairs[0] #ML 2014-09-26 topoIntImage = self._isce.topoIntImages[refPair][refPol] intImage = isceobj.createIntImage() IU.copyAttributes(topoIntImage, intImage) intImage.setAccessMode('read') objTopo = run(objFormSlc1, intImage, frame1, v, h, infos, stdWriter, catalog=catalog, sceneid=sid) self._isce.topo = objTopo
def runUnwrapIcu(infile, outfile): from mroipac.icu.Icu import Icu #Setup images #ampImage # ampImage = obj.insar.resampAmpImage.copy(access_mode='read') # width = self.ampImage.getWidth() img = isceobj.createImage() img.load(infile + '.xml') width = img.getWidth() #intImage intImage = isceobj.createIntImage() intImage.initImage(infile, 'read', width) intImage.createImage() #unwImage unwImage = isceobj.Image.createImage() unwImage.setFilename(outfile) unwImage.setWidth(width) unwImage.imageType = 'unw' unwImage.bands = 2 unwImage.scheme = 'BIL' unwImage.dataType = 'FLOAT' unwImage.setAccessMode('write') unwImage.createImage() #unwrap with icu icuObj = Icu() icuObj.filteringFlag = False icuObj.useAmplitudeFlag = False icuObj.singlePatch = True icuObj.initCorrThreshold = 0.1 icuObj.icu(intImage=intImage, unwImage = unwImage) #ampImage.finalizeImage() intImage.finalizeImage() unwImage.finalizeImage() unwImage.renderHdr()
def create_xml(fileName, width, length, fileType): if fileType == 'slc': image = isceobj.createSlcImage() elif fileType == 'int': image = isceobj.createIntImage() elif fileType == 'amp': image = isceobj.createAmpImage() elif fileType == 'float': image = isceobj.createImage() image.setDataType('FLOAT') image.setFilename(fileName) image.setWidth(width) image.setLength(length) image.setAccessMode('read') image.createImage() image.renderHdr() image.finalizeImage()
def intLooks(inps): inWidth = getWidth(inps.input + '.xml') inLength = getLength(inps.input + '.xml') outWidth = int(inWidth / inps.rlks) outLength = int(inLength / inps.alks) #run program here cmd = 'echo "{}\n{}\n{} {}\n{} {}\n" | $INSAR_ZERODOP_BIN/cpxlooks'.format( inps.input, inps.output, inWidth, inLength, inps.rlks, inps.alks) runCmd(cmd) #get xml file for interferogram intImage = isceobj.createIntImage() intImage.setFilename(inps.output) intImage.setWidth(outWidth) intImage.setLength(outLength) intImage.setAccessMode('read') #intImage.createImage() intImage.renderVRT() intImage.renderHdr()
def viewIFGstack(flip=True): ''' look at all the ifgs with napari''' import numpy as np import isceobj import napari params = np.load('params.npy', allow_pickle=True).item() stack = np.zeros((len(params['pairs']), params['nyl'], params['nxl'])) for ii in range(len(params['pairs'])): p = params['pairs'][ii] f = './merged/interferograms/' + p + '/fine_lk_filt.int' intImage = isceobj.createIntImage() intImage.load(f + '.xml') ifg = intImage.memMap()[:, :, 0] ifgc = np.angle(ifg) if flip: stack[ii, :, :] = np.flipud(ifgc) else: stack[ii, :, :] = ifgc viewer = napari.view_image(stack, colormap='RdYlBu')
def myfilt(infile, maskfile, outfile, countfile, rx, ry, newnx, newny, windowtype=2, outtype=1): windx = np.exp(-(np.arange(np.dot(-rx, 2), np.dot(rx, 2)))**2 / 2 / (rx / 2)**2) windy = np.exp(-(np.arange(np.dot(-ry, 2), np.dot(ry, 2)))**2 / 2 / (ry / 2)**2) xsum = np.sum(windx) ysum = np.sum(windy) windx = windx / xsum windy = windy / ysum ry = np.floor(len(windy) / 2) fidi = isceobj.createIntImage() fidi.load(infile + '.xml') #out files mask = np.load(maskfile) mask = mask == 1 in_ = fidi.memMap()[:, :, 0] in_ = np.exp(np.multiply(1j, in_)) in_[np.isnan(in_)] = 0 in_[~mask] = 0 good = in_ != 0 win = windx[:, np.newaxis] * windy[np.newaxis, :] goodsum = conv2(good, win, 'same') datasum = conv2(in_, win, 'same') out = datasum / goodsum #write count if countfile: np.save(countfile, goodsum) np.save(outfile, np.angle(out))
def run(resampAmpImage, infos, sceneid='NO_ID'): logger.info("Unwrapping interferogram using ICU: %s" % sceneid) wrapName = infos['outputPath'] + '.' + infos['topophaseFlatFilename'] unwrapName = infos['outputPath'] + '.' + infos['unwrappedIntFilename'] #Setup images ampImage = resampAmpImage.copy(access_mode='read') width = ampImage.getWidth() #intImage intImage = isceobj.createIntImage() intImage.initImage(wrapName, 'read', width) intImage.createImage() #unwImage unwImage = isceobj.Image.createUnwImage() unwImage.setFilename(unwrapName) unwImage.setWidth(width) unwImage.imageType = 'unw' unwImage.bands = 2 unwImage.scheme = 'BIL' unwImage.dataType = 'FLOAT' unwImage.setAccessMode('write') unwImage.createImage() #icuObj = Icu() #icuObj.filteringFlag = False ##insarApp.py already filters it icuObj = Icu(name='insarapp_icu') icuObj.configure() icuObj.initCorrThreshold = 0.1 icuObj.icu(intImage=intImage, ampImage=ampImage, unwImage=unwImage) ampImage.finalizeImage() intImage.finalizeImage() unwImage.finalizeImage() unwImage.renderHdr()
def runIonUwrap(self): '''unwrap subband interferograms ''' catalog = isceobj.Catalog.createCatalog(self._insar.procDoc.name) self.updateParamemetersFromUser() if not self.doIon: catalog.printToLog(logger, "runIonUwrap") self._insar.procDoc.addAllFromCatalog(catalog) return referenceTrack = self._insar.loadTrack(reference=True) secondaryTrack = self._insar.loadTrack(reference=False) wbdFile = os.path.abspath(self._insar.wbd) from isceobj.Alos2Proc.runIonSubband import defineIonDir ionDir = defineIonDir() subbandPrefix = ['lower', 'upper'] ionCalDir = os.path.join(ionDir['ion'], ionDir['ionCal']) os.makedirs(ionCalDir, exist_ok=True) os.chdir(ionCalDir) ############################################################ # STEP 1. take looks ############################################################ from isceobj.Alos2Proc.Alos2ProcPublic import create_xml from contrib.alos2proc.alos2proc import look from isceobj.Alos2Proc.Alos2ProcPublic import waterBodyRadar ml2 = '_{}rlks_{}alks'.format(self._insar.numberRangeLooks1*self._insar.numberRangeLooksIon, self._insar.numberAzimuthLooks1*self._insar.numberAzimuthLooksIon) for k in range(2): fullbandDir = os.path.join('../../', ionDir['insar']) subbandDir = os.path.join('../', ionDir['subband'][k], ionDir['insar']) prefix = subbandPrefix[k] amp = isceobj.createImage() amp.load(os.path.join(subbandDir, self._insar.amplitude)+'.xml') width = amp.width length = amp.length width2 = int(width / self._insar.numberRangeLooksIon) length2 = int(length / self._insar.numberAzimuthLooksIon) #take looks look(os.path.join(subbandDir, self._insar.differentialInterferogram), prefix+ml2+'.int', width, self._insar.numberRangeLooksIon, self._insar.numberAzimuthLooksIon, 4, 0, 1) create_xml(prefix+ml2+'.int', width2, length2, 'int') look(os.path.join(subbandDir, self._insar.amplitude), prefix+ml2+'.amp', width, self._insar.numberRangeLooksIon, self._insar.numberAzimuthLooksIon, 4, 1, 1) create_xml(prefix+ml2+'.amp', width2, length2, 'amp') # #water body # if k == 0: # wbdOutFile = os.path.join(fullbandDir, self._insar.wbdOut) # if os.path.isfile(wbdOutFile): # look(wbdOutFile, 'wbd'+ml2+'.wbd', width, self._insar.numberRangeLooksIon, self._insar.numberAzimuthLooksIon, 0, 0, 1) # create_xml('wbd'+ml2+'.wbd', width2, length2, 'byte') #water body if k == 0: look(os.path.join(fullbandDir, self._insar.latitude), 'lat'+ml2+'.lat', width, self._insar.numberRangeLooksIon, self._insar.numberAzimuthLooksIon, 3, 0, 1) look(os.path.join(fullbandDir, self._insar.longitude), 'lon'+ml2+'.lon', width, self._insar.numberRangeLooksIon, self._insar.numberAzimuthLooksIon, 3, 0, 1) create_xml('lat'+ml2+'.lat', width2, length2, 'double') create_xml('lon'+ml2+'.lon', width2, length2, 'double') waterBodyRadar('lat'+ml2+'.lat', 'lon'+ml2+'.lon', wbdFile, 'wbd'+ml2+'.wbd') ############################################################ # STEP 2. compute coherence ############################################################ from isceobj.Alos2Proc.Alos2ProcPublic import cal_coherence lowerbandInterferogramFile = subbandPrefix[0]+ml2+'.int' upperbandInterferogramFile = subbandPrefix[1]+ml2+'.int' lowerbandAmplitudeFile = subbandPrefix[0]+ml2+'.amp' upperbandAmplitudeFile = subbandPrefix[1]+ml2+'.amp' lowerbandCoherenceFile = subbandPrefix[0]+ml2+'.cor' upperbandCoherenceFile = subbandPrefix[1]+ml2+'.cor' coherenceFile = 'diff'+ml2+'.cor' lowerint = np.fromfile(lowerbandInterferogramFile, dtype=np.complex64).reshape(length2, width2) upperint = np.fromfile(upperbandInterferogramFile, dtype=np.complex64).reshape(length2, width2) loweramp = np.fromfile(lowerbandAmplitudeFile, dtype=np.float32).reshape(length2, width2*2) upperamp = np.fromfile(upperbandAmplitudeFile, dtype=np.float32).reshape(length2, width2*2) #compute coherence only using interferogram #here I use differential interferogram of lower and upper band interferograms #so that coherence is not affected by fringes cord = cal_coherence(lowerint*np.conjugate(upperint), win=3, edge=4) cor = np.zeros((length2*2, width2), dtype=np.float32) cor[0:length2*2:2, :] = np.sqrt( (np.absolute(lowerint)+np.absolute(upperint))/2.0 ) cor[1:length2*2:2, :] = cord cor.astype(np.float32).tofile(coherenceFile) create_xml(coherenceFile, width2, length2, 'cor') #create lower and upper band coherence files #lower amp1 = loweramp[:, 0:width2*2:2] amp2 = loweramp[:, 1:width2*2:2] cor[1:length2*2:2, :] = np.absolute(lowerint)/(amp1+(amp1==0))/(amp2+(amp2==0))*(amp1!=0)*(amp2!=0) cor.astype(np.float32).tofile(lowerbandCoherenceFile) create_xml(lowerbandCoherenceFile, width2, length2, 'cor') #upper amp1 = upperamp[:, 0:width2*2:2] amp2 = upperamp[:, 1:width2*2:2] cor[1:length2*2:2, :] = np.absolute(upperint)/(amp1+(amp1==0))/(amp2+(amp2==0))*(amp1!=0)*(amp2!=0) cor.astype(np.float32).tofile(upperbandCoherenceFile) create_xml(upperbandCoherenceFile, width2, length2, 'cor') ############################################################ # STEP 3. filtering subband interferograms ############################################################ from contrib.alos2filter.alos2filter import psfilt1 from isceobj.Alos2Proc.Alos2ProcPublic import runCmd from isceobj.Alos2Proc.Alos2ProcPublic import create_xml from mroipac.icu.Icu import Icu if self.filterSubbandInt: for k in range(2): toBeFiltered = 'tmp.int' if self.removeMagnitudeBeforeFilteringSubbandInt: cmd = "imageMath.py -e='a/(abs(a)+(a==0))' --a={} -o {} -t cfloat -s BSQ".format(subbandPrefix[k]+ml2+'.int', toBeFiltered) else: #scale the inteferogram, otherwise its magnitude is too large for filtering cmd = "imageMath.py -e='a/100000.0' --a={} -o {} -t cfloat -s BSQ".format(subbandPrefix[k]+ml2+'.int', toBeFiltered) runCmd(cmd) intImage = isceobj.createIntImage() intImage.load(toBeFiltered + '.xml') width = intImage.width length = intImage.length windowSize = self.filterWinsizeSubbandInt stepSize = self.filterStepsizeSubbandInt psfilt1(toBeFiltered, 'filt_'+subbandPrefix[k]+ml2+'.int', width, self.filterStrengthSubbandInt, windowSize, stepSize) create_xml('filt_'+subbandPrefix[k]+ml2+'.int', width, length, 'int') os.remove(toBeFiltered) os.remove(toBeFiltered + '.vrt') os.remove(toBeFiltered + '.xml') #create phase sigma for phase unwrapping #recreate filtered image filtImage = isceobj.createIntImage() filtImage.load('filt_'+subbandPrefix[k]+ml2+'.int' + '.xml') filtImage.setAccessMode('read') filtImage.createImage() #amplitude image ampImage = isceobj.createAmpImage() ampImage.load(subbandPrefix[k]+ml2+'.amp' + '.xml') ampImage.setAccessMode('read') ampImage.createImage() #phase sigma correlation image phsigImage = isceobj.createImage() phsigImage.setFilename(subbandPrefix[k]+ml2+'.phsig') phsigImage.setWidth(width) phsigImage.dataType='FLOAT' phsigImage.bands = 1 phsigImage.setImageType('cor') phsigImage.setAccessMode('write') phsigImage.createImage() icu = Icu(name='insarapp_filter_icu') icu.configure() icu.unwrappingFlag = False icu.icu(intImage = filtImage, ampImage=ampImage, phsigImage=phsigImage) phsigImage.renderHdr() filtImage.finalizeImage() ampImage.finalizeImage() phsigImage.finalizeImage() ############################################################ # STEP 4. phase unwrapping ############################################################ from isceobj.Alos2Proc.Alos2ProcPublic import snaphuUnwrap for k in range(2): tmid = referenceTrack.sensingStart + datetime.timedelta(seconds=(self._insar.numberAzimuthLooks1-1.0)/2.0*referenceTrack.azimuthLineInterval+ referenceTrack.numberOfLines/2.0*self._insar.numberAzimuthLooks1*referenceTrack.azimuthLineInterval) if self.filterSubbandInt: toBeUnwrapped = 'filt_'+subbandPrefix[k]+ml2+'.int' coherenceFile = subbandPrefix[k]+ml2+'.phsig' else: toBeUnwrapped = subbandPrefix[k]+ml2+'.int' coherenceFile = 'diff'+ml2+'.cor' snaphuUnwrap(referenceTrack, tmid, toBeUnwrapped, coherenceFile, subbandPrefix[k]+ml2+'.unw', self._insar.numberRangeLooks1*self._insar.numberRangeLooksIon, self._insar.numberAzimuthLooks1*self._insar.numberAzimuthLooksIon, costMode = 'SMOOTH',initMethod = 'MCF', defomax = 2, initOnly = True) os.chdir('../../') catalog.printToLog(logger, "runIonUwrap") self._insar.procDoc.addAllFromCatalog(catalog)
# Make the gaussian filter we'll convolve with ifg rx = 5 ry = 5 rx2 = np.floor(rx * 3) ry2 = np.floor(ry * 3) gausx = np.exp(np.divide(-np.square(np.arange(-rx2, rx2)), np.square(rx))) gausy = np.exp(np.divide(-np.square(np.arange(-ry2, ry2)), np.square(ry))) gaus = gausx[:, np.newaxis] * gausy[np.newaxis, :] gaus -= gaus.min() gaus /= np.sum(gaus.flatten()) # get slc example image (extract from an xml file) f = params['slcdir'] + '/' + dates[0] + '/' + dates[0] + '.slc.full' slcImage = isceobj.createSlcImage() slcImage.load(f + '.xml') intimg = isceobj.createIntImage() intimg.width = slcImage.width intimg.length = slcImage.length for ii, d in enumerate(dates[:-1]): if not os.path.isfile(params['slcdir'] + '/' + d + '/fine_diff.int') or overwrite: print('working on ' + d) d2 = dates[ii + 1] #load ifg real and imaginary parts f = params['slcdir'] + '/' + d + '/' + d + '.slc.full' slcImage = isceobj.createSlcImage() slcImage.load(f + '.xml') slc1 = slcImage.memMap()[:, :, 0] f = params['slcdir'] + '/' + d2 + '/' + d2 + '.slc.full' slcImage = isceobj.createSlcImage() slcImage.load(f + '.xml')