def GetImageSubset(subsetparameters, data, dimensions): #------------------------------------------------------------------ # Create square image subset from predefined corner points #------------------------------------------------------------------ Point = subsetparameters.Point # get and scale image subset BoxRange = dimensions.BoxRange BoxRange = BoxRange.astype(int) image = data.image[Point[1] - BoxRange[0]:Point[1] + BoxRange[1], Point[0] - BoxRange[0]:Point[0] + BoxRange[1]] image = IP.ScaleImage(image, 8) # get and store corresponding coordinates easting = data.coordinates.easting[Point[1] - BoxRange[0]:Point[1] + BoxRange[1], Point[0] - BoxRange[0]:Point[0] + BoxRange[1]] northing = data.coordinates.northing[Point[1] - BoxRange[0]:Point[1] + BoxRange[1], Point[0] - BoxRange[0]:Point[0] + BoxRange[1]] coordinates = CL.Coordinates(northing, easting) #store subset data FlagFlip = IP.CheckImageOrientation(coordinates) subset = CL.Subset(Point, image, coordinates, data.resolution, FlagFlip) return subset
def GetGtiffInformation(filein,EPSG=0): # open file and get information f, a, img = ReadGtiffRaster(filein) # metadata Metadata = f.GetMetadata() # dimension ncols, nrows = a.XSize, a.YSize # ground control points GCPs = f.GetGCPs() GCPs_projection = f.GetGCPProjection() # transformation info (coordinates and resolution) Geotransform = f.GetGeoTransform() # projection info (spatial reference system (EPSG related)) if EPSG == 0: srs = osr.SpatialReference(wkt=f.GetProjection()) else: srs = osr.SpatialReference(); srs.ImportFromEPSG(EPSG) #store information Infos = CL.GtiffInformation(Metadata, ncols, nrows, GCPs, GCPs_projection, Geotransform, srs) #deallocate raster f = None return img, Infos
def DefineLine(img, direction, point, FlagOrtho): #----------------------------------------------- # Define line slope, offset and equation #----------------------------------------------- fac = np.pi / 180 # image dimension dim = img.shape # determine line coefficients a = np.tan(fac * direction) # slope if FlagOrtho == 1: # orthogonal slope a*a'=-1 a = -1 / a b = point[1] - a * point[0] # constant # estimate line x = np.linspace(0, dim[0] - 1, dim[0]) y = a * x + b # store data lined = CL.line(x, y, a, b) return lined
def GetBoxDim(subsetparameters, subset): #------------------------------------------------------------------ # defined box dimension as a function of : # - image resolution # - domain length (m) : 1000m<length<2000m #------------------------------------------------------------------ # rough estimate of the box dimension in pixel DimensionPixel = np.int( np.round(((subsetparameters.DomainDimension) / subset.resolution[0]))) # refine dimension for computation efficiency if subsetparameters.FlagPowerofTwo: # dimension as a functionnearest power of 2 power = np.round(np.log(DimensionPixel) / np.log(2)) DimensionPixel = 2**power else: # dimension as a combination of simple prime numbers (2,3,5,...) DimensionPixel = cv2.getOptimalDFTSize(DimensionPixel) # box dimension in meter DimensionMeters = DimensionPixel * subset.resolution[0] # range from center BoxRange = np.zeros(2) + np.int(np.round(DimensionPixel / 2.)) residual = np.mod(DimensionPixel, 2) if residual > 1: BoxRange[0] = np.int(np.round(DimensionPixel / 2.)) - 1 # store data dimension = CL.SubsetDimension(DimensionPixel, DimensionMeters, BoxRange) return dimension
def GetImageGridPointsIndices(data, ResolutionPixels): #---------------------------------------------------------------------------------------- # # Create Grid according to the image dimension and user-defined resolution # #---------------------------------------------------------------------------------------- GlobalGridPoints = [] # get image dimension easting = data.coordinates.easting[0, :] northing = data.coordinates.northing[:, 0] nx = easting.shape[0] ny = northing.shape[0] # create points indices arrays IndicesX = GridSubSampling(nx, ResolutionPixels) IndicesY = GridSubSampling(ny, ResolutionPixels) X, Y = np.meshgrid(IndicesX, IndicesY) # flatten the arrays for fast computation indx = X.flatten() indy = Y.flatten() # gather all information about grid points for i in range(indx.shape[0]): indexx = indx[i] indexy = indy[i] east = easting[indexx] north = northing[indexy] Point = CL.GridPoints(east, north) GlobalGridPoints.append(Point) # array format GlobalGridPoints = np.asarray(GlobalGridPoints) return GlobalGridPoints
def DetectLineEdge(img, lined): #------------------------------------------------------------ # Detect intersection points of image edges by a given line #------------------------------------------------------------ # initialization point1 = np.zeros(2) point2 = np.zeros(2) dim = img.shape # Detect intersection with image edge m = np.min(lined.y) M = np.max(lined.y) if m < 0: point1[0] = np.int(np.rint(-lined.b / lined.a)) point1[1] = 0 else: point1[0] = 0 point1[1] = np.int(np.rint(lined.b)) yy = dim[1] - 1 xx = dim[0] - 1 if M > yy: point2[1] = yy point2[0] = np.int(np.rint((yy - lined.b) / lined.a)) else: point2[0] = xx point2[1] = np.int(np.rint(lined.a * xx + lined.b)) # store data edpt = CL.edgepoint(point1, point2) return edpt
def GetImageGridPoints(data, ResolutionPixels): #---------------------------------------------------------------------------------------- # # Create Grid according to the image dimension and user-defined resolution # #---------------------------------------------------------------------------------------- GlobalGridPoints = [] # get image dimension easting = data.coordinates.easting[0, :] northing = data.coordinates.northing[:, 0] # create points indices arrays Easting = GridSubSampling(easting, ResolutionPixels) Northing = GridSubSampling(northing, ResolutionPixels) E, N = np.meshgrid(Easting, Northing) # flatten the arrays for fast computation East = E.flatten() North = N.flatten() # gather all information about grid points for i in range(East.shape[0]): Point = CL.GridPoints(East[i], North[i]) GlobalGridPoints.append(Point) # array format GlobalGridPoints = np.asarray(GlobalGridPoints) return GlobalGridPoints
def Direction_PeakDetection(parameters, theta, distribution, Flag): #------------------------------------ # peak detection #------------------------------------ # domain dichotomy angle = 360 - UT.CartesianNautical( parameters.CoastNormalOrientation) if Flag else UT.CartesianNautical( parameters.CoastNormalOrientation) theta1, distribution1, theta2, distribution2 = DirectionDichotomy( theta, distribution, angle) Directions = np.zeros(2) # parameter for peak detection ratio = 20. / 100 if parameters.submethod in { 'clusterpower', 'ClusterPower', 'centroidpower', 'CentroidPower' }: power = 2 else: power = 1 PeakParameters = CL.PeakParameters(power, ratio) # data for peak detection DataDirection1 = CL.DataPeak(theta1, distribution1) DataDirection2 = CL.DataPeak(theta2, distribution2) # estimate mean direction Directions[0] = UT.PeakDetection(PeakParameters, parameters.submethod, DataDirection1) Directions[1] = UT.PeakDetection(PeakParameters, parameters.submethod, DataDirection2) flagplot = 0 if flagplot > 0: fig, ax1 = plt.subplots(1) ax1.plot(theta1, distribution1, 'o') ax1.plot(theta2, distribution2, 'o') ax1.axvline(x=Directions[0]), ax1.axvline(x=Directions[1]) ax1.axhline(y=ratio * np.max(distribution1)), ax1.axhline( y=ratio * np.max(distribution2)) plt.show() return Directions
def Array2List(array): #--------------------------------------------------------------------- # # convert numpy coordinate array coordinate into a list of data # #---------------------------------------------------------------------- data = [] for i in range(array.shape[0]): if array.shape[1] == 1: point = CL.GridPoints(array[i, 0]) elif array.shape[1] == 2: point = CL.GridPoints(array[i, 0], array[i, 1]) elif array.shape[1] == 3: point = CL.GridPoints(array[i, 0], array[i, 1], array[i, 2]) data.append(point) data = np.asarray(data) return data
def WavelengthEstimate(ComputingParameters, k, spectrum): #----------------------------------------- # Estimate Peak Wavelength #---------------------------------------- # parameters if ComputingParameters.SpectrumParameters.WaveSpectrumParameters.SpectrumType == 'Radial': kth = 0.01 data = CL.DataPeak(k[np.where(k > kth)], spectrum[np.where(k > kth)]) else: data = CL.DataPeak(k, spectrum) WavelengthParameters = ComputingParameters.SpectrumParameters.WavelengthEstimationParameters peak_parameters = CL.PeakParameters(WavelengthParameters.Power) # mean wavenumber estimate PeakWavenumber = UT.PeakDetection( peak_parameters, WavelengthParameters.PeakDeterminationMethod, data) # wavelength PeakWavelength = 2 * np.pi / PeakWavenumber return PeakWavelength
def RemoveBathymetryException(parameters, Points, Bathymetry): #------------------------------------------------------------------------------------------------------------------- # # Remove Grid points impacted with bathymetry exception # #-------------------------------------------------------------------------------------------------------------------- # remove NaN bathymetry values point, bathymetry, northing, easting = RemoveNanBathymetry( Points, Bathymetry) # remove land-sea interpolation artefacts #point, bathymetry, northing, easting = RemoveBathymetryAnomalies(parameters, point, bathymetry, northing, easting) coordinates = CL.Coordinates(northing, easting) BathymetryData = CL.BathymetryData(coordinates, bathymetry) """ fig, ax = plt.subplots(1) for i in range(bathymetry.shape[0]): ax.plot(i, bathymetry[i],'or') """ return point, BathymetryData
def InputSubsetParameters(): #----------------------------------------------- # Image Processing input parameters #----------------------------------------------- #input arguments parser = argparse.ArgumentParser(description='Co-ReSyF: SAR Bathymetry Research Application') #image parser.add_argument('-a', '--param', help='Parameters file for Wings (.ini file)', default='Config_Image.ini',required=False) parser.add_argument('-i', '--input', help='Input image (to be processed)', required=True) parser.add_argument('-b','--bathymetry', help='Bathymetric grid in a txt or npz file',required=True) parser.add_argument('-p', '--processing', nargs='+', help='Image Processing Filters (Slant Range Correction, ContrastStretch)', default=[True, True], required=False) parser.add_argument('-r', '--reference_system', nargs='+', help='Spatial Reference system EPSG code (Selected Image and Projection, cf. gdalinfo for image information and \ http://spatialreference.org/ref/epsg/)', required=True) #subscene parser.add_argument('-o', '--output', nargs='+', help='List with output file names (subsets#.out) for FFT determination (to be used by Wings)', required=False) parser.add_argument('-d', '--dimension', help='Dimension of the subscenes (meters, ideally 1000-2000m)', default=2000., required=False) parser.add_argument('-w', '--window', help='number of overlapping boxes for FFT computation', default=9, required=False) parser.add_argument('-s', '--shift', help='Overlapping boxes offset parameters for FFT computation. Values between (0.1-0.75). Default=0.5.',default=0.5, required=False) # peak wave period parser.add_argument('-T', '--Tp', help='mean peak wave period Tp', default=0, required=False) #comments parser.add_argument('-v','--verbose', help="comments and screen outputs", action="store_true") # store args = parser.parse_args() RunId = datetime.now().strftime('%Y%m%dT%H%M%S') #create config.ini file parOut = open(args.param, "w"); Config = ConfigParser.ConfigParser(); Config.add_section("Arguments") #image Config.set("Arguments", "Input_image", args.input); Config.set("Arguments", "Bathymetry_file", args.bathymetry) Config.set("Arguments", "Image_processing_filters", args.processing); Config.set("Arguments", "Reference_systems", args.reference_system) #subscene Config.set("Arguments", "Subscene_list", args.output); Config.set("Arguments", "Box_dimension", args.dimension) Config.set("Arguments", "Number_of_boxes", args.window); Config.set("Arguments", "Box_shift", args.shift) Config.add_section("Run") Config.set("Run", "Id", RunId) Config.write(parOut); parOut.close() # check which filters to apply Contrast_Stretch = True if (any("contrast" in s for s in args.processing) or any("contrast" in s for s in args.processing)) else False Slant_Correction = True if (any("slant" in s for s in args.processing) or any("Slant" in s for s in args.processing)) else False # store data in classes file_path_name = CL.File_path_name('', args.input, '', '') Point = np.zeros(2) + 1000; Point = Point.astype(int) LandMask_Parameters = CL.LandMaskParameters() ProcessingParameters = CL.Processing_Parameters('uint16', Slant_Correction, 1., Contrast_Stretch, LandMask_Parameters) SpatialReferenceSystem = CL.Spatial_Reference_System(args.reference_system[0], args.reference_system[1]) Subsetparameters = CL.SubsetParameters(Point, float(args.dimension), True, float(args.shift), int(float(args.window))) Image_Parameters = CL.ImageParameters(file_path_name, ProcessingParameters, SpatialReferenceSystem) return Subsetparameters, Image_Parameters, args, args.verbose
def Get_apriori_bathymetry(parameters, points): # transform input data Coordinates = PointsList2Coordinates(points) # Find Collocated bathymetry coord, bathy = FindCollocatedBathymetry(parameters.BathymetryParameters, Coordinates) bathydata = CL.BathymetryData(coord, bathy) # interpolate bathymetry on the grid points Bathymetry_Data = InterpolateBathymetry(parameters.MiscellaneousParameters, Coordinates, bathydata) return Bathymetry_Data
def MergeSpectrumData(points): #--------------------------------------------------- # gather all 2D spectrum data in exploitable arrays #--------------------------------------------------- # get array size k, Spectra, SpectraStd = [point.Spectrum.WaveSpectrum.k for point in points], [point.Spectrum.WaveSpectrum.Spectrum for point in points], \ [point.Spectrum.WaveSpectrum.StandardDeviation for point in points] # store and save data fname = os.getcwd() + '/Output/Bathymetry/WaveSpectrum.out' data = CL.SpectrumProcessedData(np.asarray(k), np.asarray(Spectra), np.asarray(SpectraStd)) data.pickle(fname) return k, Spectra
def GetFFTBoxes(subsetparameters, data, dimension): #--------------------------------------------------------------------------------------------------------------- # Create list of overlapping subset images to estimate spectrum at a given grid point (center of main subset) #--------------------------------------------------------------------------------------------------------------- # initialisation #images, northings, eastings= [],[],[] Subsets = [] # Get the various subset images centers (box defined with an offset from the main subset, the overlapping is controlled by the offset) offset = subsetparameters.Shift * dimension.BoxRange subset_centers = GetSubsetCenters(subsetparameters.Point, offset, subsetparameters.BoxNb) # get information on subsets (coordinates, image footprint) for i in subset_centers: # get subset subsetparameters.Point = i subset = GetImageSubset(subsetparameters, data, dimension) # scale image image = IP.ScaleImage(subset.image, 8) coordinates = CL.Coordinates(subset.coordinates.northing, subset.coordinates.easting) FlagFlip = IP.CheckImageOrientation(coordinates) subsets = CL.Subset(i, image, coordinates, data.resolution, FlagFlip) Subsets.append(subsets) """ # concatenate data images.append(image); eastings.append(subset.coordinates.easting); northings.append(subset.coordinates.northing) #store data coordinates = Coordinates(northings,eastings) subsets = Subset(subset_centers, images, coordinates, data.resolution) """ return Subsets
def CreatePolygon(indices, image, easting, northing): #---------------------------------------------- # create a polygonial region of interest (ROI) #---------------------------------------------- ROI_points = [] for i in range(indices.shape[0]): indx, indy = indices[i, 0], indices[i, 1] # indices East, North = easting[indx], northing[indy] # coordinates cv2.circle(image, (indx, indy), 10, (255, 255, 255), -1) # plot points point = CL.GridPoints(East, North) # store points ROI_points.append(point) ROI_points = np.asarray(ROI_points) return ROI_points
def PointsList2Coordinates(points): #----------------------------------------- # Convert points list in Coordinates list #------------------------------------------ easting, northing = [], [] for point in points: easting.append(point.easting) northing.append(point.northing) easting = np.asarray(easting) northing = np.asarray(northing) coordinates = CL.Coordinates(northing, easting) return coordinates
def Create_Subset_TransferFile(index, parameters, point, SubsetData, outlist): #----------------------------------------------------------------------- # Create transfer file to save grid point subsets data and information #------------------------------------------------------------------------ # path and filename cwd = os.getcwd() path = cwd + '/' fname = 'subset' if outlist: transfer_file = path + outlist[index] else: transfer_file = path + fname + str(index) + '.out' # gather data Subset = CL.SubsetTransferData(parameters, point, SubsetData) # save data Subset.pickle(transfer_file)
def DirectDepthInversion(point, Tp): #------------------------------------------------------------------------------- # # perform direct inversion (Tp known (hydrodynamic input or computed offshore)) # #------------------------------------------------------------------------------- # depth inversion depth = DepthEstimate(point.wavelength, Tp) # store data ComputedPoint = CL.GridPointsData(point.IndexEasting, point.IndexNorthing, point.easting, point.northing, point.apriori_bathymetry, point.Spectrum, point.wavelength, point.DiscriminationFlag, Tp, -depth) return ComputedPoint
def InterpolateBathymetry(parameters, Coordinates, bathydata): #------------------------------------------------------------------------ # Find Collocated bathymetry corresponding to the input data coordinates #------------------------------------------------------------------------ #initialization # grid points easting = Coordinates.easting northing = Coordinates.northing npt = easting.shape[0] bathymetry = np.zeros(npt) # current bathymetry coord = bathydata.Coordinates bathy = bathydata.Bathymetry e, n = np.meshgrid(coord.easting, coord.northing) #interpolate on the grid points if parameters.InterpolationMethod == 'multiquadric': rbfi = Rbf(e, n, bathy) bathymetry = rbfi(easting, northing) else: bathymetry = griddata((e.ravel(), n.ravel()), bathy.ravel(), (easting, northing), method=parameters.InterpolationMethod) BathymetryData = CL.BathymetryData(Coordinates, bathymetry) """ fig, ax = plt.subplots(1) cl=np.array([-200,-20]) ea = coord.easting; no = coord.northing; ax.imshow(bathy, cmap=plt.cm.jet, interpolation=None, aspect='auto', origin='upper', extent=[np.min(ea), np.max(ea), np.min(no), np.max(no)], vmin=cl[0], vmax=cl[1]) cm = plt.get_cmap("jet") for i in range(easting.shape[0]): convcol = 255*(bathymetry[i]-cl[0])/(cl[1]-cl[0]); col = cm(convcol.astype(int)) ax.plot(easting[i], northing[i], color=col, marker='o',markeredgecolor='k'); plt.show() """ return BathymetryData
def ReadGtiffBathymetry(parameters): #----------------------------------------- # READ EMODNET BATHYMETRY #----------------------------------------- # Read bathymetry (Gtiff format) coordinate, depth, _ = IP.ReadSARImg(parameters) # process bathymetry # depth to bathymetry bathymetry = -depth # Land Mask bathymetry[bathymetry > 0] = np.nan # create vector coordinate (instead of ) east = coordinate.easting[0, :] north = coordinate.northing[:, 0] coordinates = CL.Coordinates(north, east) return coordinates, bathymetry
def ImageSpectrum(parameters, subset): #---------------------------------------------- # Compute Image Spectrum or Power Spectrum #---------------------------------------------- image = subset.image # given subset image if parameters.MeanSubstractionFlag: image = image - np.mean(image) # substract mean value Spectrum = imfft(image) # FFT of the given image mag = cv2.magnitude(Spectrum[:, :, 0], Spectrum[:, :, 1]) if parameters.DecibelRepresentationFlag: mag = 20 * np.log(mag) # amplitude spectrum (sqrt(Im**2 +Re**2)) #power Spectrum S = Spectrum[:, :, 0] + 1j * Spectrum[:, :, 1] mag2 = np.real(S * np.conjugate(S)) if parameters.DecibelRepresentationFlag: mag2 = 20 * np.log(mag2) #mag2 = np.abs(mag)**2 # selected spectrum to be plotted if parameters.PowerSpectrumFlag == True: spectrum = mag2 else: spectrum = mag #-------------------------------- # define the wavenumber axis #-------------------------------- step = 1 / subset.resolution[0] freqs = np.linspace(0, (spectrum.shape[1] - 1) * step / spectrum.shape[1], spectrum.shape[1]) fCenter = 0.5 * (freqs[np.int(spectrum.shape[1] / 2)] + freqs[np.int(spectrum.shape[1] / 2) - 1]) freqs = freqs - fCenter # axis centered on 0 k = 2 * np.pi * (freqs) #store data ImageSpectrum = CL.SpectrumData(k, spectrum) return ImageSpectrum
def ReadTopography(parameters): #----------------------------------------------------- # Read Topography file to extract #----------------------------------------------------- parameter = parameters.ProcessingParameters.LandMaskParameters filename = parameter.LandMaskFileName; path_input = parameter.LandMaskFilePath; path_output=parameters.File_path_name.path_output pattern ='/' if sys.platform=='win32': pattern = '\\' # get projection information EPSG_in = GetDataProjectionSystem(path_input+filename) # reproject topography in the selected output reference coordinate system EPSG_out = GetEPSG(parameters.SpatialReferenceSystem.EPSG_Flag_Out) if EPSG_in != EPSG_out: file_aux = filename[:-4].split(pattern)[-1]+"_projected_EPSG"+str(EPSG_out)+".tif"; flin = path_input + filename; fout = path_output + file_aux; if not os.path.isfile(fout): os.system("gdalwarp -overwrite -srcnodata 0 -dstnodata 0 -r average -t_srs EPSG:"+str(EPSG_out)+" "+flin+" "+fout) else: print file_aux," Already Exists..." flin = file_aux path = path_output else: path = path_input # read raster filename= path + flin f, _, topography = ReadGtiffRaster(filename,'float32') f = None # process exception topography[np.isnan(topography)] = 0 # get Coordinates northing, easting = GetNorthingEasting(filename) coordinates = CL.Coordinates(northing[:,0], easting[0,:]) return coordinates, topography
def array2raster(img, coordinates, EPSG, filein, fileout="ImgOut.tif"): #------------------------------------------------------------ # convert 2D array into GDAL raster (GeoTiff) # General purpose: recreate raster after # - change in frame of reference # - conserve the Projection system #------------------------------------------------------------ # get input infos _,Info = GetGtiffInformation(filein, EPSG) #process image img=ScaleImage(img,8) # get corner coordinates # coordinates easting = coordinates.easting; northing = coordinates.northing; # extrema xmin,ymin,xmax,ymax = [easting.min(),northing.min(),easting.max(),northing.max()] if len(img.shape)>2: nrows,ncols = np.shape(img[0,:,:]) else: nrows,ncols = np.shape(img) # store dimension data Info.ncols = ncols; Info.nrows=nrows; #get the edges and recreate the corner coordinates for Geotransform raster properties xres = (xmax-xmin)/float(ncols); yres = (ymax-ymin)/float(nrows) Geotransform = (xmin,xres,0,ymax,0, -yres); Infos = CL.GtiffInformation(Info.Metadata, Info.ncols, Info.nrows, Info.GCPs, Info.GCPs_projection, Geotransform, Info.srs) #create output raster CreateOutputGtiff(img, fileout, Infos) return None
def ReadGridPoints(args, coordinates): #---------------------------------------------------------------------- # # find image pixel that correspond to the grid point # #---------------------------------------------------------------------- # image coordinates Easting = coordinates.easting[0, :] Northing = coordinates.northing[:, 0] # grid points coordinates points, flagbathy = ReadPointsfromGridFile(args.bathymetry) # find correspondance grid / image Points = [] for point in points: indE = np.argmin(np.abs(Easting - point.easting)) indN = np.argmin(np.abs(Northing - point.northing)) data = CL.GridPointsData(indE, indN, Easting[indE], Northing[indN], point.apriori_bathymetry) Points.append(data) Points = np.asarray(Points) return Points, flagbathy
def CollocatedData(Coordinates, coord, data): #------------------------------------------------------------------------------------------------------------------- # ESTIMATE COLLOCATED COORDINATES AND data # # Remark: data (bathymetry/topography) domain should be bigger than image domain if grid points are different #-------------------------------------------------------------------------------------------------------------------- east = coord.easting north = coord.northing East = Coordinates.easting North = Coordinates.northing # check if image was flipped flagE = False FlagN = False if east[0] > east[-1]: flagE = True if north[0] > north[-1]: flagN = True # Image limit (Coordinate-wise, (W, E, S, N)) W = np.min(East) E = np.max(East) S = np.min(North) N = np.max(North) # find nearest collocated coordinates iW = np.argmin(abs(W - east)) iE = np.argmin(abs(E - east)) iS = np.argmin(abs(S - north)) iN = np.argmin(abs(N - north)) # verify that bathymetry domain is bigger if east[iW] > W: if flagE: iW = iW + 1 else: iW = iW - 1 if east[iE] < E: if flagE: iE = iE - 1 else: iE = iE + 1 if north[iS] > S: if flagN: iS = iS + 1 else: iS = iS - 1 if north[iN] < N: if flagN: iN = iN - 1 else: iN = iN + 1 # coordinates easting = east[iW:iE + 1] northing = north[iN:iS + 1] coordinates = CL.Coordinates(northing, easting) # bathymetry Data = data[iN:iS + 1, iW:iE + 1] return coordinates, Data
def ReadSARImg(parameters): #------------------------------------------------------------ # Read/process SAR images and get related information #------------------------------------------------------------ # define EPSG code according to frame of reference # (WGS84/4326: Geodesic, WGS84/32629: UTM zone 29N, ETRS89/3763: portugal projection) EPSG_in = GetEPSG(parameters.SpatialReferenceSystem.EPSG_Flag_In) EPSG_out = GetEPSG(parameters.SpatialReferenceSystem.EPSG_Flag_Out) # Input/Output path and files path_input = parameters.File_path_name.path_input; fname_input = parameters.File_path_name.fname_input; path_output = parameters.File_path_name.path_output; #path delimiter pattern ='/' if sys.platform=='win32': pattern = '\\' #************************** # A) Raw image #************************** #------------------------------------------------------------------------------------- # PROCESS IMAGE # Get image specific format and dimension filein = fname_input; flin = path_input + filein; ImgType, ImgSize, ImgRes = GetImgType(flin), GetImgSize(flin), GetImRes(flin) f, RasterBand, img = ReadGtiffRaster(flin,parameters.ProcessingParameters.DataType) # slant range correction if parameters.ProcessingParameters.SlantRangeCorrection_Flag: if (ImgType["ENVISAT"] or ImgType["ERS1/2"] or ImgType["GeoTIFF"]): fileout_slant = fname_input[:-4]+"_Slant.tif"; fout = path_input + fileout_slant SlantRangeGTiFF(flin,fout, EPSG_in) filein = fileout_slant # Scale image if parameters.ProcessingParameters.ScaleFactor!=1.: file_aux = filein[:-4].split(pattern)[-1]+"_scaled.tif"; flin = path_input + filein; fout = path_input + file_aux; dim = (int(ImgSize[1]*ScaleFactor), int(ImgSize[0]*ScaleFactor)) if not os.path.isfile(fout): print "\nCreating an "+EPSG_flag+" image file..." os.system("gdalwarp -overwrite -srcnodata 0 -dstnodata 0 -r average -ts "+str(dim[0])+" "+str(dim[1])+" -t_srs EPSG:"+str(EPSG_in)+" "+flin+" "+fout) else: print file_aux," Already Exists..." filein = file_aux #------------------------------------------------------------------------------------- #************************** # B) Projected image #************************** # IMAGE PROJECTION if EPSG_in != EPSG_out: file_aux = filein[:-4].split(pattern)[-1]+"_projected_EPSG"+str(EPSG_out)+".tif"; flin = path_input + filein; fout = path_output + file_aux; if not os.path.isfile(fout): os.system("gdalwarp -overwrite -srcnodata 0 -dstnodata 0 -r average -t_srs EPSG:"+str(EPSG_out)+" "+flin+" "+fout) else: print file_aux," Projected image Already Exists..." filein = file_aux path = path_output else: path = path_input # get Image type and dimensions flin = path + filein ImgType = GetImgType(flin); ImgSize = GetImgSize(flin); #------------------------------------------------------------------------------------- # GET IMAGE INFORMATION # get northing/easting and pixel resolution (m) from projected image northing, easting, res = GetProjImgInfo(flin) # gather all coordinates coordinates = CL.Coordinates(northing,easting) # read projected image and get raster image f, _, img = ReadGtiffRaster(flin, parameters.ProcessingParameters.DataType) # close raster f = None #------------------------------------------------------------------------------------- # PROCESS IMAGE # stretch contrast (CS is the reference image) if parameters.ProcessingParameters.ContrastStretch_Flag: img = ImageContrastStretch(coordinates, img, flin, EPSG_out) else: flin = path + filein; fout = path_output + filein[:-4].split(pattern)[-1] + "_CS.tif" os.system("cp " + flin + " " + fout) #create land mask if parameters.ProcessingParameters.LandMaskParameters.LandMaskFlag: filename = filein[:-4].split(pattern)[-1]+"_Masked.tif" if not os.path.isfile(path+filename): # create image mask mask = CreateLandMask(flin, coordinates, parameters) ind = (mask>0) # save masked image array2raster(img, coordinates, EPSG_out, flin, path+filename) else: print filename," Masked image Already Exists..." f, _, mask = ReadGtiffRaster(path+filename); f = None; ind = (mask==0) # superpose mask on image img[ind] = 0 else: LMaskFile = flin mask = img """ fig, ax = plt.subplots(1) E=coordinates.easting; N=coordinates.northing; ax.imshow(img, cmap=plt.cm.gray, interpolation=None, aspect='auto', origin='upper', extent=[np.min(E), np.max(E), np.min(N), np.max(N)]) plt.show() """ return coordinates, img, res
def DefinePolygonalROI(data): #------------------------------------------------------------------------------------------------- # create a polygonial region of interest (ROI) to crop the image and perform wavelength estimation #------------------------------------------------------------------------------------------------- # load data image = data.image image = cv2.convertScaleAbs(image) easting = data.coordinates.easting northing = data.coordinates.northing # resize image parameters (reduce resolution) fac = 5 dimension = (np.round(image.shape[0] / fac), np.round(image.shape[1] / fac)) # resize image image = UT.ResizeArray(image, dimension) northing = UT.ResizeArray(northing, dimension) easting = UT.ResizeArray(easting, dimension) # clone image clone = image.copy() N = northing.copy() E = easting.copy() Northing = N[:, 0] Easting = E[0, :] # initialize list of points: reference points (corners) indices and coordinates ReferencePoints, ContourCoordinates = [], [] # image attribute for cropping with OpenCV points = CL.StoreIndices() cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.resizeWindow('image', 600, 600) cv2.setMouseCallback('image', points.select_point) # display options print """ #################################### # Press 'r' to reset points. # # Press 's' to save points. # # Press 'q' to quit. # #################################### """ # loop to create ROI while True: # display image cv2.imshow('image', image) key = cv2.waitKey(1) & 0xFF # reset if key == ord("r"): del points.indices[0:] image = clone.copy() # quit elif key == ord("q"): cv2.destroyWindow("image") break # define and save ROI elif key == ord("s"): # save selected points indices = np.asarray(points.indices) # check the number of selected points (2-> rectangle, 3 or + -> polygon) dimension = indices.shape[0] if dimension < 3: ROI_points, indices = CreateRectangle(indices, image, Easting, Northing) else: ROI_points = CreatePolygon(indices, image, Easting, Northing) #print domain edges cv2.polylines(image, [indices.reshape((-1, 1, 2))], True, (255, 255, 255), 2) # change data format return ROI_points
def CreateLandMask(filein, coordinates_image, parameters): #----------------------------------------------------- # create Land Mask using selected topography file #----------------------------------------------------- #******************************************************* # 0) get information on the output system of reference #******************************************************* EPSG_out = GetEPSG(parameters.SpatialReferenceSystem.EPSG_Flag_Out) kernel = np.ones((5,5),np.uint8) #************************** # A) band mask from image #************************** mask = CreateBandMask(filein) indexS = (mask>0); indexM = (mask==0) mask[indexS] = 0; mask[indexM] = 255 # create band mask northing, easting = GetNorthingEasting(filein) # retrieve coordinates coordinates_image = CL.Coordinates(northing[:,0], easting[0,:]) #process / dilate mask edge if parameters.ProcessingParameters.LandMaskParameters.FilterFlag: mask = cv2.dilate(mask, kernel,iterations = 2) # save raster to temporary file fileout_image = 'ImageMask.tif'; array2raster(mask, coordinates_image, EPSG_out, filein, fileout_image) #****************************** # B) band mask for topography #****************************** # read topography file Coordinates, Topography = ReadTopography(parameters) #read topography # collocated topography coordinates, topography = ROI.CollocatedData(coordinates_image, Coordinates, Topography) # find collocated topography (reference: image coordinates) indexS = (topography==0); indexL = (topography!=0) # distinguish between topography[indexS] = 0; topography[indexL] = 255 # create mask #process / dilate mask edge if parameters.ProcessingParameters.LandMaskParameters.FilterFlag: topography = cv2.dilate(topography, kernel,iterations = 2) # create mask raster fileout_mask='TopographyMask.tif'; array2raster(topography, coordinates, EPSG_out, filein, fileout_mask) #********************* # C) merge both masks #********************* filename = fileout_image # the mask is pasted into the image mask file (mandatory for gdal_merge to keep dimensions) os.system("gdal_merge.py -n 0. -o "+fileout_image+" "+fileout_mask+" "+ filename) # merge mask image using gdal_merge f, _, finalmask = ReadGtiffRaster(filename,'float32'); f = None; # read mask os.system("rm"+" "+fileout_mask+" "+fileout_image) # clean directory """ #-------- # figure #-------- fig, (ax1,ax2,ax3) = plt.subplots(3) # image mask E = coordinates_image.easting; N = coordinates_image.northing; ax1.imshow(mask, cmap=plt.cm.jet, interpolation=None, aspect='auto', origin='upper', extent = [np.min(E), np.max(E), np.min(N), np.max(N)]) # topography mask E = coordinates.easting; N = coordinates.northing; ax2.imshow(topography, cmap=plt.cm.jet, interpolation=None, aspect='auto', origin='upper', extent = [np.min(E), np.max(E), np.min(N), np.max(N)]) #merge mask E = coordinates_image.easting; N = coordinates_image.northing; ax3.imshow(finalmask, cmap=plt.cm.jet, interpolation=None, aspect='auto', origin='upper', extent = [np.min(E), np.max(E), np.min(N), np.max(N)]) plt.show() """ return finalmask
def DiscriminatedGroups(parameters, Points): #---------------------------------------------------------------------------------------- # Gather points in groups (DW, nDW, SW or other) and affect a method for depth inversion #---------------------------------------------------------------------------------------- Points = np.asarray(Points) # look for exception points (Deep Water or shallow water) DWpoints, SWpoints, nDWpoints, Otherpoints, GlobalPoints = [], [], [], [], [] for point in Points: flag = point.DiscriminationFlag if flag == 0: Tp = WavePeriodEstimate(point.wavelength, abs(point.apriori_bathymetry)) pt = CL.GridPointsData(point.IndexEasting, point.IndexNorthing, point.easting, point.northing, point.apriori_bathymetry, point.Spectrum, point.wavelength, flag, Tp, point.apriori_bathymetry) DWpoints.append(pt) elif flag == -1: pt = CL.GridPointsData(point.IndexEasting, point.IndexNorthing, point.easting, point.northing, point.apriori_bathymetry, point.Spectrum, point.wavelength, flag, 0, np.nan) SWpoints.append(pt) else: Otherpoints.append(point) # gather points DWpoints = np.asarray(DWpoints) SWpoints = np.asarray(SWpoints) ExceptionPoints = CL.ExceptionPoints(DWpoints, SWpoints) # if no deep water points look for near deep water point lDW = len(DWpoints) Otherpoints = np.asarray(Otherpoints) if lDW == 0 and parameters.InversionMethod != 'direct': nDWpoints = [] for point in Otherpoints: flag = point.DiscriminationFlag if flag == 0.5: nDWpoints.append(point) else: GlobalPoints.append(point) else: GlobalPoints = Otherpoints #gather points nDWpoints = np.asarray(nDWpoints) GlobalPoints = np.asarray(GlobalPoints) ComputationPoints = CL.ComputationPoints(GlobalPoints, nDWpoints) # sum up grid point status print 'total number of points', len(Points) print 'number exception points', len(DWpoints) + len(SWpoints) print '- number of deep water points', len(DWpoints) print '- number of shallow water points', len(SWpoints) print 'number Computation points', len(nDWpoints) + len(GlobalPoints) print '- number of quasi deep water points', len(nDWpoints) print '- number of normal computation points', len(GlobalPoints) # if no deep or near deep water points only direct method is used if (len(DWpoints) == 0) and (len(nDWpoints) == 0): method = 'direct' else: method = parameters.InversionMethod return ExceptionPoints, ComputationPoints, method