Exemple #1
0
def preProcess_IMERGD():
    inPath="F:/Test/GraduationWork/Data/IMERG/"
    ncPath=inPath+"Daily_nc_V06/"
    outTifPath=inPath+"Daily_tif_0.1/"
    outHBALPath = inPath + "Daily_HBAL/"
    outResampledPath=inPath+"Daily_HBAL_0.05/"
    workspace=inPath + "0/"
    mask="F:/Test/GraduationWork/Data/HB/"+"HubeiAreaLarge.shp"
    for f in os.listdir(ncPath):
        env.workspace=workspace
        ncfile=os.path.join(ncPath,f)
        date=f.split('-')[1].split('.')[-1]

        layer = 'nc_' + date
        arcpy.MakeNetCDFRasterLayer_md(ncfile, "precipitationCal", "lon", "lat", layer)  # "nc制作图层"

        outTif=outTifPath+"IMERGD_"+date+".tif"
        arcpy.Resample_management(layer, outTif, "0.1", "BILINEAR")

        outExtractByMask = arcpy.sa.ExtractByMask(outTif, mask)
        outHBAL=outHBALPath+"IMERGD_"+date+"_HBAL"+".tif"
        outExtractByMask.save(outHBAL)

        outTif = outResampledPath + "Resampled_IMERGD_" + date + "_HBAL"+".tif"
        arcpy.Resample_management(outHBAL, outTif, "0.05", "BILINEAR")
        print("{} is done!".format(date))
        # break

    return 0
Exemple #2
0
def resample(inRaster,outRaster):
	if os.path.isdir(outRaster):
		print("Removing "+outRaster)
		#os.rm("D:/Users/cmarciniak/My Documents/GLDAS/rasters/resample.aux.xml")
		#shutil.rmtree(outRaster)
		arcpy.Resample_management(inRaster,outRaster,.05)
	else:
		print("Resampling...")
		arcpy.Resample_management(inRaster,outRaster,.05)
	print("Done")
Exemple #3
0
def CreateUnsuitableSlopes(in_dem, outUnsuitSlope):
    arcpy.ProjectRaster_management(in_dem, "project", spatial_ref)
    x = arcpy.Describe("project").meanCellWidth
    y = arcpy.Describe("project").meanCellHeight
    cellSizeXY = "{} {}".format(x, y)
    #print(cellSizeXY)
    arcpy.Resample_management("project", "resample", cellSizeXY, "CUBIC")
    arcpy.Delete_management("project")
    # Run slope generation
    slope_raster = arcpy.sa.Slope("resample", "PERCENT_RISE")
    outInt = arcpy.sa.Int(slope_raster)
    arcpy.Delete_management("resample")
    del slope_raster
    # Set parameters for raster Reclassification as a boolean
    max_slope = outInt.maximum
    myRemapRange = arcpy.sa.RemapRange([[0, 10, 0], [10, int(max_slope), 1]])
    ### Run reclassification
    outReclassRR = arcpy.sa.Reclassify(outInt, "Value", myRemapRange)  #
    del outInt
    ### Query Bad Slopes
    #arcpy.ProjectRaster_management(outInt, "project", spatial_ref)
    slope_unSuit = arcpy.sa.ExtractByAttributes(outReclassRR, 'Value = 1')
    del outReclassRR
    ## Convert to Vector
    arcpy.RasterToPolygon_conversion(slope_unSuit,
                                     outUnsuitSlope,
                                     raster_field="Value")
    del slope_unSuit
    # Clean up geometry
    arcpy.RepairGeometry_management(outUnsuitSlope)
Exemple #4
0
def create_chm(rootdir):
    """
    Resamples the DTM to the resolution of the DSM and then subtracts the
    resampled DTM from the DSM to create a Canopy Height Model (CHM)

    Assumes directory structure of rootdir\refID\sensor\output...
    """
    arcpy.CheckOutExtension("3d")
    ## Needed ffor the Minus_3d tool
    refIDs = []
    for subdir in os.listdir (rootdir):
        refIDs.append(rootdir + "\\" + subdir)
    for refID in refIDs:
        sensors =  ["\\Mavic", "\\Sequoia"]
        for sensor in sensors:
            layers = ""
            for root, dirs, files in os.walk(refID + sensor + "\\Output"):
                for dir in dirs:
                    ##excludes directories containing only tiles
                    if "tiles" in dirs:
                        dirs.remove("tiles")
                for file in files:
                    if file.endswith("dsm.tif"):
                        DSM = os.path.join(root,file)
                    if file.endswith("dtm.tif"):
                        DTM = os.path.join(root,file)
                        CellSize = arcpy.GetRasterProperties_management(DSM, property_type = "CELLSIZEX")
                        ## Defining cell size to resample the DTM to that of the DSM- known
                        ##bug for doing so in the Resample_management tool.
                        ##BUG!!! https://community.esri.com/thread/162982
                        DTMrsmpl = refID + sensor + "\\Output" + "\\DTMrsmpl.tif"
                        arcpy.Resample_management(DTM, DTMrsmpl, CellSize )
                        ## Subtract DTM (resampled) from DSM to create CHM
                        arcpy.Minus_3d(DSM, DTMrsmpl, refID + sensor + "\\Output" + sensor +"CHM.tif")
                        print (refID + sensor + " CHM Created")
Exemple #5
0
def f1():

    ##########
    arcpy.env.workspace = ""
    rasters = arcpy.ListRasters()
    mask=""
    for raster in rasters:
        out = ExtractByMask(raster, mask)   #"按掩膜提取"
        out.save("xxx/_34.tif")

        arcpy.Resample_management(raster, out, "xres yres", "BILINEAR")  # "NEAREST ","BILINEAR","CUBIC","MAJORITY" #"重采样"

        arcpy.ExtractSubDataset_management("xxx.hdf", "outfile.tif", "2")   #"提取子数据集,第三个参数是选择提取第几个子数据集(波段)"

        layer=""
        arcpy.MakeNetCDFRasterLayer_md(raster, "precipitation", "lon", "lat", layer)      # "nc制作图层"
        arcpy.CopyRaster_management(layer, out, format="TIFF")  # "图层保存为栅格"

        ExtractValuesToPoints(mask, raster,out, "INTERPOLATE","VALUE_ONLY") # "值提取到点"/"NONE","INTERPOLATE"/"VALUE_ONLY","ALL"

        out= SetNull(raster, raster, "Value=-3000") # "将满足条件的像元值设为Nodata"

        out=CellStatistics(rasters, out, "SUM", "NODATA")   # "像元统计" "MEAN/MAJORITY/MAXIMUM/MEDIAN/MINIMUM/MINORITY/RANGE/STD/SUM/VARIETY "    "NODATA"/"DATA"忽略nodata像元
        out.save("xxx.img")

        arcpy.Delete_management(raster) # "删除文件"

        rasters = arcpy.ListRasters()   # "数据的重命名"
        for raster in rasters:
            raster.save("xxx.tif")

        arcpy.TableToExcel_conversion(mask, "xxx.xls")# "表转Excel"

        arcpy.DirectionalDistribution_stats(raster, out, "1_STANDARD_DEVIATION", "xxx", "#")# "标准差椭圆"
        arcpy.MeanCenter_stats(raster, out, "xxx", "#", "#")    # "中心"
Exemple #6
0
def resample_and_clip(cellsize, feature_path, raster_dir):
    temp_raster = raster_dir + "\\temp.tif"
    if arcpy.Exists(temp_raster):
        arcpy.Delete_management(temp_raster)
    for file in os.listdir(raster_dir):
        if file.endswith(".tif"):
            raster = raster_dir + "\\" + file
    resampled_raster = "in_memory\\resampled"
    resampled_cellsize = str(cellsize) + ' ' + str(cellsize)
    arcpy.Resample_management(raster, resampled_raster, resampled_cellsize,
                              "BILINEAR")
    envelope = "in_memory\\envelope"
    buffer = "in_memory\\buffer"
    envelope = arcpy.FeatureEnvelopeToPolygon_management(
        feature_path, envelope, "SINGLEPART")
    buffer = arcpy.Buffer_analysis(envelope, buffer, 500, "FULL", "ROUND",
                                   "NONE", "", "PLANAR")
    rows = arcpy.SearchCursor(buffer)
    shapeName = arcpy.Describe(buffer).shapeFieldName
    for row in rows:
        feat = row.getValue(shapeName)
        extent = feat.extent
        envelope = str(extent.XMin) + ' ' + str(extent.YMin) + ' ' + str(
            extent.XMax) + ' ' + str(extent.YMax)
    arcpy.Clip_management(resampled_raster, envelope, temp_raster)
    arcpy.Delete_management("in_memory")
    return
Exemple #7
0
def resample(input_raster, output_location, state_abbrev, county_name):
    ##
    ## This function reprojects the selected raster to 2m resolution.
    ##
    ## Input Variables:
    ##      input_raster:   The file location of the native NAIP imagery.
    ##                       This is likely in 1m resolution, but may be
    ##                       as small as .3m in some states like California.
    ##
    ##      output_location:    The path to the folder where the reprojected file should
    ##                           be placed in. This does not include the filename.
    ##
    ##      state_abbrev & county_name: The respective state abbreviation, 'NC' for
    ##                                   example, and the respective county name,
    ##                                   such as 'Union'.
    ##
    state_name = nameFormat(state_abbrev_to_name[state_abbrev])
    county_name = nameFormat(county_name)

    outputName = 'NAIP2m_' + state_abbrev + '_' + county_name
    if not arcpy.Exists(os.path.join(output_location, outputName)):
        if arcpy.Exists(input_raster):
            print "Resampling", state_abbrev, county_name, "..."
            arcpy.Resample_management (input_raster, os.path.join(output_location, outputName), \
                                        cell_size="2 2", resampling_type="NEAREST")

            print state_abbrev, county_name, "resampled. Script duration so far:", checkTime(
            )
        else:
            print "--", state_abbrev, county_name, "input NAIP imagery not found."
    else:
        print "-- Resampled raster for", state_abbrev, county_name, "already exists!"
Exemple #8
0
def CalcZonalStats(in_zone_data, zone_field, in_value_raster, out_table):
    """
    Resamples inValueRaster to 5m pixel size and calculates the average value
    within each map unit. Higher resolution required for map units <5 acres.
    :param in_zone_data: the Map Units Dissolve feature class
    :param zone_field: the field to use as zone field, must be integer and
    cannot be OBJECTID
    :param in_value_raster: raster dataset or basename as a string
    :param out_table: a name to save the ouput table as a string
    :return: None
    """
    # Convert null values to 0 so that they are not ignored when summarizing
    in_value_raster = Con(IsNull(in_value_raster),0,in_value_raster)

    # Resample to avoid small map units returning null values
    resample = True
    if resample:
        # Resample raster
        tmp_raster = "sub_raster"
        arcpy.Resample_management(in_value_raster, tmp_raster, "5", "NEAREST")
    else:
        tmp_raster = in_value_raster
    # Calculate zonal statistics
    arcpy.gp.ZonalStatisticsAsTable_sa(in_zone_data, zone_field, tmp_raster,
                                    out_table, "DATA", "MEAN")
    if resample:
        arcpy.Delete_management(tmp_raster)
def ExtMatch(year_day, band, clipshp, tiffile, arcrast, prjfile, foldername):
    """This function matches all rasters to the same grid. It resamples when necessary using bilinear resampling.
    Returns the clipped version of the input dataset."""
    
    arcpy.env.snapRaster = arcrast
    arcpy.env.extent = clipshp

    outprj = TMP + year_day + '_' + band + '_tightprj.tif'
    arcpy.ProjectRaster_management(tiffile, outprj, prjfile, 'BILINEAR', '30')
                
    out_tight = TMP + year_day + "_" + band + '_' + foldername + "_tight.tif"
    cliptif = arcpy.sa.ExtractByMask(outprj, clipshp)
    cliptif.save(out_tight)
    del cliptif
    arcpy.Delete_management(outprj)

    cell = arcpy.GetRasterProperties_management(out_tight, 'CELLSIZEX')
    cellsize = cell.getOutput(0)
    if cellsize <> 30:
        out_tight_res = TMP + year_day + "_" + band + "_tight_res.tif"
        arcpy.Resample_management(out_tight, out_tight_res, '30', 'BILINEAR') #Resample all datasets to same resolution
        arcpy.Delete_management(out_tight)
        arcpy.CopyRaster_management(out_tight_res, out_tight)
        arcpy.Delete_management(out_tight_res)

    return out_tight
Exemple #10
0
def N1():
    inPath="F:/Test/GraduationWork/Data/IMERG/"
    ncPath=inPath+"Daily_nc_V06/"
    outTifPath=inPath+"Daily_tif_0.1/"
    outMaskedPath = inPath + "Daily_mainLandChina_0.1/"
    outResampledPath=inPath+"Daily_mainLandChina_0.05/"

    workspace=inPath + "0/"
    mask="F:/Test/GraduationWork/Data/HB/"+"mainLandChina_V2.shp"
    for f in os.listdir(ncPath):
        env.workspace=workspace
        ncfile=os.path.join(ncPath,f)
        date=f.split('-')[1].split('.')[-1]

        outTif=outTifPath+"IMERGD_"+date+".tif"
        # arcpy.Resample_management(layer, outTif, "0.1", "BILINEAR")

        outExtractByMask = arcpy.sa.ExtractByMask(outTif, mask)
        outMasked=outMaskedPath+"IMERGD_"+date+"_MainLand_0.1"+".tif"
        outExtractByMask.save(outMasked)

        outResampled = outResampledPath + "IMERGD_"+date+"_MainLand_0.05"+".tif"
        arcpy.Resample_management(outMasked, outResampled, "0.05", "BILINEAR")
        print("{} is done!".format(date))
        # break

    return 0
def fun_resample(in_raster, out_raster):
    """Resample the raster resolution to the new resolution defined earlier and save the new raster"""
    out_scratch_str = (arcpy.env.scratchWorkspace + "\\" + out_raster)
    arcpy.Resample_management(in_raster,
                              out_scratch_str,
                              cell_size=new_res_value_float,
                              resampling_type='BILINEAR')
Exemple #12
0
        def run(IFile, Ofile, Snumx, Snumy, Stype):
            from arcpy import env
            env.overwriteOutput = "True"
            print "--------------------------------------------------------------------"
            print "Program GetCentroid Starts: ", time.asctime(
                time.localtime(time.time()))
            print "--------------------------------------------------------------------"
            try:
                import arcpy
                from arcpy import env
                arcpy.env.workspace = Ofile
                cell = Snumx + " " + Snumy
                # Resample TIFF image
                arcpy.Resample_management(IFile, "resamplenew.tif", cell,
                                          Stype)

                inRaster = "resamplenew.tif"
                outPoint = Ofile + "/outpoint.shp"
                field = "VALUE"
                arcpy.RasterToPoint_conversion(inRaster, outPoint, field)

                print "Input corret, output file has been generated..!"
                print "--------------------------------------------------------------------"
                print "Program GetCentroid Ends: ", time.asctime(
                    time.localtime(time.time()))
                print "--------------------------------------------------------------------"

            except:
                print "Resample example failed."
                print arcpy.GetMessages()
Exemple #13
0
    def onClick(self):
        print "Nettoyage de la couche matricielle..."
        arcpy.Resample_management("classified raster", "resample", "0,3 0,3", "NEAREST")

        # Process: Boundary Clean
        arcpy.gp.BoundaryClean_sa("resample", "boundaryC", "NO_SORT", "TWO_WAY")

        # Process: Focal Statistics
        arcpy.gp.FocalStatistics_sa("boundaryC", "focalS", "Rectangle 6 6 CELL", "MAJORITY", "DATA")

        # Process: Focal Statistics (2)
        arcpy.gp.FocalStatistics_sa("focalS", "cleaned_raster", "Rectangle 6 6 CELL", "MAJORITY", "DATA")

        # Dé-sélection des couches inutiles
        selectedLayers = ["classified raster", "resample", "boundaryC", "focalS"]
        mxd = arcpy.mapping.MapDocument("current")
        df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
        layers = arcpy.mapping.ListLayers(mxd, "*", df)

        for layer in layers:
            if layer.name in selectedLayers:
                layer.visible = False

        arcpy.RefreshTOC()
        arcpy.RefreshActiveView()
    def execute(self, parameters, messages):
        '''The source code of the tool.'''
        in_rasterdataset = parameters[0].valueAsText
        in_fc = parameters[1].valueAsText
        in_cellsize = parameters[2].valueAsText
        in_field = parameters[3].valueAsText

        arcpy.env.workspace = in_rasterdataset

        ## check workspace and raster files
        rasterlist = arcpy.ListRasters("*")
        arcpy.PolygonToRaster_conversion(in_features=in_fc,
                                         value_field=in_field,
                                         out_rasterdataset="snap1",
                                         cellsize=in_cellsize)
        snap = "snap1"
        arcpy.AddMessage("Snap Raster Created")

        ## Project, resample, and clip rasters
        for raster in rasterlist:
            Ras = arcpy.Raster(raster)
            arcpy.env.snapRaster = snap
            projrast1 = arcpy.ProjectRaster_management(Ras, "proj1", snap,
                                                       "NEAREST")
            resamprast1 = arcpy.Resample_management(projrast1, "resamp1",
                                                    in_cellsize, "NEAREST")
            cliprast = arcpy.Clip_management(resamprast1, "#",
                                             raster + "_final", in_fc, "0",
                                             "ClippingGeometry")
            arcpy.AddMessage("Snap Raster Created")

        ## Delete temp files
        arcpy.Delete_management("resamp1")
        arcpy.Delete_management("proj1")
def execute_Resample(smoothed_dir, dem3m_dir, flow_dir, frompoints_dir,
                     prefixe, river_tools_folder, output_folder, messages):

    sys.path.append(river_tools_folder)
    from Breach import execute_Breach

    arcpy.env.workspace = smoothed_dir
    rasterlist = arcpy.ListRasters()

    flowdir_output = arcpy.CreateScratchName(
        "rres",
        data_type="RasterDataset",
        workspace=arcpy.env.scratchWorkspace)
    temp_resample = arcpy.CreateScratchName(
        "rres",
        data_type="RasterDataset",
        workspace=arcpy.env.scratchWorkspace)
    temp_tobreach = arcpy.CreateScratchName(
        "rres",
        data_type="RasterDataset",
        workspace=arcpy.env.scratchWorkspace)

    arcpy.env.extent = flow_dir

    for raster in rasterlist:
        print(raster)

        buffered = arcpy.sa.Float(
            arcpy.sa.EucAllocation(arcpy.sa.Int(
                arcpy.Raster(raster) * 1000))) / 1000
        with arcpy.EnvManager(snapRaster=flow_dir):
            arcpy.Resample_management(
                buffered, temp_resample,
                str(flow_dir.meanCellWidth) + " " +
                str(flow_dir.meanCellHeight), "BILINEAR")
        dem3m = os.path.join(dem3m_dir, raster)
        tobreach = arcpy.sa.ExtractByMask(temp_resample, dem3m)
        tobreach.save(temp_tobreach)

        newextent = str(tobreach.extent.XMin) + " " + str(
            tobreach.extent.YMin) + " " + str(
                tobreach.extent.XMax) + " " + str(tobreach.extent.YMax)
        arcpy.Clip_management(flow_dir,
                              newextent,
                              flowdir_output,
                              maintain_clipping_extent="MAINTAIN_EXTENT")

        str_frompoints = os.path.join(frompoints_dir,
                                      prefixe + raster + ".shp")
        result = os.path.join(output_folder, raster)

        with arcpy.EnvManager(extent=flow_dir):
            execute_Breach(arcpy.Raster(temp_tobreach),
                           arcpy.Raster(flowdir_output), str_frompoints,
                           result, messages)

    arcpy.Delete_management(flowdir_output)
    arcpy.Delete_management(temp_resample)
    arcpy.Delete_management(temp_tobreach)
Exemple #16
0
 def _resample_processor(self, file_path):
     """ Resample image to coarse or fine cell size """
     out_res_ras = self._create_file_name(
         file_path)  # Create new file name from existing file
     print('Resampling..... {}'.format(ntpath.basename(file_path)))
     upper_res_method = self.res_method.upper()
     arcpy.Resample_management(file_path, out_res_ras, self.cell_size,
                               upper_res_method)
def hydroresample(in_vardict,
                  out_vardict,
                  in_hydrotemplate,
                  resampling_type='NEAREST'):
    templatedesc = arcpy.Describe(in_hydrotemplate)

    # Check that all in_vardict keys are in out_vardict (that each input path has a matching output path)
    keymatch = {l: l in out_vardict for l in in_vardict}
    if not all(keymatch.values()):
        raise ValueError(
            'All keys in in_vardict are not in out_vardict: {}'.format(
                [l for l in keymatch if not keymatch[l]]))

    # Iterate through input rasters
    for var in in_vardict:
        outresample = out_vardict[var]

        if not arcpy.Exists(outresample):
            print('Processing {}...'.format(outresample))
            arcpy.env.extent = arcpy.env.snapRaster = in_hydrotemplate
            arcpy.env.XYResolution = "0.0000000000000001 degrees"
            arcpy.env.cellSize = templatedesc.meanCellWidth
            print('%.17f' % float(arcpy.env.cellSize))

            try:
                arcpy.Resample_management(in_raster=in_vardict[var],
                                          out_raster=outresample,
                                          cell_size=templatedesc.meanCellWidth,
                                          resampling_type=resampling_type)
            except Exception:
                print("Exception in user code:")
                traceback.print_exc(file=sys.stdout)
                arcpy.ResetEnvironments()

        else:
            print('{} already exists...'.format(outresample))

        # Check whether everything is the same
        maskdesc = arcpy.Describe(outresample)

        extentcomp = maskdesc.extent.JSON == templatedesc.extent.JSON
        print('Equal extents? {}'.format(extentcomp))
        if not extentcomp:
            print("{0} != {1}".format(maskdesc.extent, templatedesc.extent))

        cscomp = maskdesc.meanCellWidth == templatedesc.meanCellWidth
        print('Equal cell size? {}'.format(cscomp))
        if not cscomp:
            print("{0} != {1}".format(maskdesc.meanCellWidth,
                                      templatedesc.meanCellWidth))

        srcomp = compsr(outresample, in_hydrotemplate)
        print('Same Spatial Reference? {}'.format(srcomp))
        if not srcomp:
            print("{0} != {1}".format(maskdesc.SpatialReference.name,
                                      templatedesc.SpatialReference.name))

    arcpy.ResetEnvironments()
def _create_parameter_region_grid(dem, shp, shp_att_name, parreg_in, parreg):
    if os.path.exists(parreg):
        os.remove(parreg)

    if shp is None and parreg_in is None:
        Utils.initialize_output_raster_file(dem, parreg, initial_data=1, data_type=gdal.GDT_UInt32)
    else:
        # determine cell size from the dem
        base_raster_file_obj = gdal.Open(dem, GA_ReadOnly)
        geotransform = base_raster_file_obj.GetGeoTransform()
        pixelWidth = geotransform[1]

        if shp:

            # This environment settings needed  for the arcpy.PlogonToRaster_conversion function
            # env.extent = dem
            # env.snapRaster = dem
            # print (">>> setting the environment for polygon to raster conversion")
            # TODO: try if we can use the gdal api to convert shape file to raster instead of arcpy
            # Ref: https://pcjericks.github.io/py-gdalogr-cookbook/raster_layers.html
            # utils.initialize_output_raster_file(dem, parreg, initial_data=1, data_type=gdal.GDT_Int32)
            # target_ds = gdal.Open(parreg)

            # For some reason the gdal RasterizeLayer function works with a in memory output raster dataset only
            target_ds = _create_in_memory_raster(dem, data_type=gdal.GDT_UInt32)
            source_ds = ogr.Open(shp)
            source_layer = source_ds.GetLayer()
            # Rasterize
            err = gdal.RasterizeLayer(target_ds, [1], source_layer, options=["ATTRIBUTE=%s" % shp_att_name])
            if err != 0:
                raise Exception(err)
            else:
                # save the in memory output raster to the disk
                gdal.GetDriverByName(Utils.GDALFileDriver.TifFile).CreateCopy(parreg, target_ds)

            target_ds = None
            source_ds = None

            # arcpy.PolygonToRaster_conversion(shp, shp_att_name, temp_shp_raster, "CELL_CENTER", "NONE", str(pixelWidth))
            # arcpy.ResetEnvironments()

        elif parreg_in:
            # TODO: This one only gets the grid cell size to the size in dem file
            # but it doesn't get the output grid size (rows and cols) same as the dem
            temp_parreg = os.path.join(os.path.dirname(dem), 'temp_parreg.tif')
            if os.path.exists(temp_parreg):
                arcpy.Delete_management(temp_parreg)
                # os.remove(temp_parreg)
            target_ds = _create_in_memory_raster(dem, data_type=gdal.GDT_UInt32)
            # utils.initialize_output_raster_file(dem, parreg, initial_data=utils.NO_DATA_VALUE, data_type=gdal.GDT_UInt32)
            # arcpy.Resample_management(parreg_in, parreg, str(pixelWidth), "NEAREST")
            arcpy.Resample_management(parreg_in, temp_parreg, str(pixelWidth), "NEAREST")
            # save the in memory output raster to the disk
            source_ds = gdal.Open(temp_parreg, GA_ReadOnly)
            gdal.ReprojectImage(source_ds, target_ds, None, None, gdal.GRA_NearestNeighbour)
            source_ds = None
            gdal.GetDriverByName(Utils.GDALFileDriver.TifFile).CreateCopy(parreg, target_ds)
            arcpy.Delete_management(temp_parreg)
def resample(in_dir, out_dir):
    # ndvi_8km_dir = this_root+'CCI\\0.25\\tif\\'
    # ndvi_0_5_dir = this_root+'CCI\\0.5\\tif\\'
    mk_dir(out_dir)
    for f in os.listdir(in_dir):
        if f.endswith('.tif'):
            print(f)
            arcpy.Resample_management(in_dir + f, out_dir + f, "0.5",
                                      "NEAREST")
Exemple #20
0
def resample30m():
    ndvi_8km_dir = this_root + 'PDSI\\tif\\'
    ndvi_0_5_dir = this_root + 'PDSI\\tif_resample_0.5\\'
    mk_dir(ndvi_0_5_dir)
    for f in os.listdir(ndvi_8km_dir):
        if f.endswith('.tif'):
            print(f)
            arcpy.Resample_management(ndvi_8km_dir + f, ndvi_0_5_dir + f,
                                      "0.5", "NEAREST")
def fun_resample_DEM(in_raster, out_raster, mask_bool):
    """Mask and resample the DEM resolution to the new resolution defined earlier and save the new raster"""
    out_str = (arcpy.env.scratchWorkspace + "\\" + out_raster)
    if mask_bool:
        in_raster = arcpy.sa.ExtractByMask(in_raster, mask)
    arcpy.Resample_management(in_raster,
                              out_str,
                              cell_size=new_res_value_float,
                              resampling_type='BILINEAR')
Exemple #22
0
def resample30m():
    fvc_1km_dir = this_root+'FVC_1km_new\\FVC-year_1km_clipped_0_100\\'
    # fvc_30m_dir = this_root+'30m年值_1978_1985_1995_2005_2018\\'
    # fvc_30m_tif = this_root+'30m年值_1978_1985_1995_2005_2018\\LC08_2018.tif'
    out_dir = this_root+'FVC_1km_new\\1km_30m_cubic\\'
    mkdir(out_dir)
    for f in os.listdir(fvc_1km_dir):
        if f.endswith('.tif'):
            print(f)
            arcpy.Resample_management(fvc_1km_dir+f,out_dir+f,"27.0427354","CUBIC")
Exemple #23
0
def exportbands(timeband, inputproperties, inputfilepath, outputpath):
    '''
    Within the NetCDF processing loop we create raster files
    and save them to new folders.

    Take date arguments...

    Along with the dimension value, the input file, and the
    output file.
    '''

    # Grab a string value and the date value from current band.
    dimension_date, dimension_value = sub_getdatefromcurrentband(
        inputproperties, timeband)

    # Parse date variable of current file into logical chunks.
    # The string is in the Month/Day/Year format:
    filemonth, fileday, fileyear = sub_processdatesfromnetcdf(dimension_date)

    # Make filename from year, month, and day:
    arguments = [noaafile_type, fileyear, filemonth, fileday]
    outputrastername = '_'.join(map(str, arguments))
    print('Exporting raster {}.tif'.format(outputrastername))

    # Take CURRENT dimensions from current NetCDF.
    # Pull current layer out as raster layer in memory named 'outfilename'.
    # rainfall (PRATE) is the value that will be mapped.

    makenetcdf = arcpy.MakeNetCDFRasterLayer_md(inputfilepath, "prate", "lon",
                                                "lat", "temporaryraster", "",
                                                dimension_value, "BY_VALUE")

    # Convert in-memory raster layer to a saved layer, also named 'outfilename'.
    outputrasterfile = os.path.join(outputpath,
                                    ''.join([outputrastername, '.tif']))

    arcpy.AddMessage("Writing " + outputrastername)

    # Resample raster such that resultant raster has half the X and Y dimensions
    # This will make each raster having second column perfectly aligned by prime meridian
    arcpy.Resample_management("temporaryraster", outputrasterfile,
                              "0.9375 0.94747340425532", "NEAREST")

    # Clip first column of each raster (the only column that lies in -X dimension)
    arcpy.Clip_management(outputrasterfile, "-0.9375 -90.054779 0 88.070221",
                          "clip", "", "", "NONE", "NO_MAINTAIN_EXTENT")

    # Mosaic the first column of each raster to the original raster
    # ArcGIS will automatically take care of converting -ve X values to +ve
    arcpy.Mosaic_management("clip", outputrasterfile, "LAST", "LAST", "0", "9",
                            "", "", "")

    print makenetcdf.getMessages()
    arcpy.Delete_management(outputrastername)
    arcpy.Delete_management("in_memory")
Exemple #24
0
def f8_GCS():
    path = 'F:/Test/Paper180829/Data/LTN/'
    arcpy.env.workspace = path + 'monthlyLTN/'
    rasters = arcpy.ListRasters()
    for raster in rasters:
        # outResample=path+'0.0125d_rawLTN/'+raster
        # arcpy.Resample_management(raster, outResample, "0.0125", "BILINEAR")   #"重采样到0.1度"
        #
        # mask='F:/Test/Paper180829/Data/HB/'+'HB8048.shp'
        # outExtract = ExtractByMask(outResample, mask)   #"按掩膜提取"
        # outExtract.save(path+'0.0125d_LTN_HB8048/'+raster)
        #
        # outAggreg = Aggregate(outExtract, 8, "MEAN", "EXPAND", "DATA")
        # outAggreg.save(path+'0.1d_LTN_HB8048/'+raster)
        #
        # points='F:/Test/Paper180829/Data/POINT/'+'POINTS3840.shp'
        # outPoints=path + '0.1d_LTN_RG3840/' +raster[0:9]+'.shp'
        # ExtractValuesToPoints(points, outExtract, outPoints, "INTERPOLATE", "VALUE_ONLY")  #"值提取到点"
        #
        # arr = arcpy.da.FeatureClassToNumPyArray(outPoints, ('RASTERVALU'))
        # # np.savetxt(path + '0.1d_LTN_Txts/' +raster[0:9]+'.txt',arr,fmt = '%.8f')
        # # print arr
        #
        # outExcels = path + '0.1d_LTN_Excels/' + raster[0:9] + '.xlsx'
        # workbook = xlsxwriter.Workbook(outExcels)
        # worksheet = workbook.add_worksheet('0.1d_LTN')  # originIMERG 0.1dIMERG
        # # print len(arr),arr[0],arr[0][0]
        # for i in range(0, len(arr)):
        #     worksheet.write(i, 0, arr[i][0])
        # workbook.close()

        outResample = path + '0.01d_rawLTN/' + raster
        arcpy.Resample_management(raster, outResample, "0.01",
                                  "BILINEAR")  # "重采样到0.1度"

        mask = 'F:/Test/Paper180829/Data/HB/' + 'HB8048.shp'
        outExtract = ExtractByMask(outResample, mask)  # "按掩膜提取"
        outExtract.save(path + '0.01d_LTN_HB8048/' + raster)

        points = 'F:/Test/Paper180829/Data/POINT/' + 'POINTS384000.shp'
        outPoints = path + '0.01d_LTN_RG384000/' + raster[0:9] + '.shp'
        ExtractValuesToPoints(points, outExtract, outPoints, "INTERPOLATE",
                              "VALUE_ONLY")  # "值提取到点"

        arr = arcpy.da.FeatureClassToNumPyArray(outPoints, ('RASTERVALU'))
        # np.savetxt(path + '0.01d_LTN_Txts/' +raster[0:9]+'.txt',arr,fmt = '%.8f')
        # print arr
        outExcels = path + '0.01d_LTN_Excels/' + raster[0:9] + '.xlsx'
        workbook = xlsxwriter.Workbook(outExcels)
        worksheet = workbook.add_worksheet(
            '0.01d_LTD')  # originIMERG 0.1dIMERG
        # print len(arr),arr[0],arr[0][0]
        for i in range(0, len(arr)):
            worksheet.write(i, 0, arr[i][0])
        workbook.close()
Exemple #25
0
def extractDTM(projectPath):
    # set path variable to the user input & grab project name from input
    pathName = projectPath
    pathArr = pathName.split('\\')
    aoi = pathArr[len(pathArr) - 1]
    campaign = pathArr[3]
    collectionYear = campaign.split('-')[2]
    buffer = 1500
    fpDir = r"Y:\vexcel\source\%s\%s\Metadata\FootprintShapefile" % (campaign,
                                                                     aoi)
    terrainLayer = 'https://elevation.arcgis.com/arcgis/rest/services/WorldElevation/Terrain/ImageServer'

    # grab the shapefile for the project
    if path.exists(fpDir):
        for shp in os.listdir(fpDir):
            if fnmatch.fnmatch(shp, '*.shp'):
                fpSHP = shp

        # grab the prj file for the project
        for prj in os.listdir(fpDir):
            if fnmatch.fnmatch(prj, '*.prj'):
                fpPRJ = prj

    # set the path to the shapefile and prj file
    shpPath = fpDir + '\\' + fpSHP
    prjPath = fpDir + '\\' + fpPRJ

    print('--> pathName  ' + pathName + '\n--> aoi  ' + aoi +
          '\n --> campaign  ' + campaign + '\n --> collectionYear  ' +
          collectionYear + '\n--> fpSHP  ' + fpSHP + '\n--> fpPRJ  ' + fpPRJ)

    # setting the output coordinate system to match the footprint prj file
    arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(prjPath)

    # handling for 2018 and 2019 differences in the dtm path
    if collectionYear == '2019':
        dtm = 'Y:\\vexcel\\source\\%s\\%s\\esri-mosaic-dataset\\dtm\\dtm.tif' % (
            campaign, aoi)
    else:
        dtm = 'Y:\\vexcel\\source\\%s\\%s\\EsriMosaicDataset\\DTM\\dtm.tif' % (
            campaign, aoi)

    # getting the extent
    desc = arcpy.Describe(shpPath)
    extent = '{} {} {} {}'.format(desc.extent.XMin - buffer,
                                  desc.extent.YMin - buffer,
                                  desc.extent.XMax + buffer,
                                  desc.extent.YMax + buffer)

    # setting the environment extent
    arcpy.env.extent = extent

    # running the resample tool
    print(' ------- running resample now ------- ')
    arcpy.Resample_management(terrainLayer, dtm, "10 10", "NEAREST")
def Resize():
    locations = "E:/Project/EToASC_/"
    dirs = os.listdir(locations)
    global cell_size

    for file in tqdm(dirs):
        in_raster = locations + file
        out_raster = "E:/Project/EToASC_MID/" + file.rstrip(".asc") + ".tif"
        arcpy.Resample_management(in_raster, out_raster, cell_size)
        outASCII = "E:/Project/EToASC/" + file
        arcpy.RasterToASCII_conversion(out_raster, outASCII)
Exemple #27
0
def arcResampleRasters(FileList=["f1.tif","f2.tif"],inPath=None,outPath=None,resolution="C:\\templateRaster.tif"):
	import arcpy, os
	if inPath==None: inPath=os.getcwd()
	if outPath==None: 
		outPath=os.getcwd()+"\\resampled"
		os.mkdir(outPath)
	
	inFileList = list()
	outFileList = list()
	if type(FileList) is list():
		for f in FileList:
			inFilePath = inPath+'\\'+f
			outFilePath = outPath+'\\'+f
			#Rescale Function Call 
			arcpy.Resample_management(inFilePath, outFilePath, resolution,"CUBIC")
	else:
		inFilePath = inPath+'\\'+FileList
		outFilePath = outPath+"\\resampled_"+FileList
		arcpy.Resample_management(inFilePath, outFilePath, resolution,"CUBIC")
	print("completed rescale of files @ location:", outPath)
Exemple #28
0
def resample(cellsize, raster_dir):
    temp_raster = raster_dir + "\\temp.tif"
    if arcpy.Exists(temp_raster):
        arcpy.Delete_management(temp_raster)
    for file in os.listdir(raster_dir):
        if file.endswith(".tif"):
            raster = raster_dir + "\\" + file

    resampled_cellsize = str(cellsize) + ' ' + str(cellsize)
    arcpy.Resample_management(raster, temp_raster, resampled_cellsize,
                              "BILINEAR")
Exemple #29
0
def zonal_NLDAS_timeseries(sdate, edate, site_id, band, a_basin):
    """
    Given a month and location, get values from NLDAS raster
    """
    date = sdate
    ts = []
    dates = []
    oldws = arcpy.env.workspace
    arcpy.env.workspace = 'K:/GIS/MODEL/output/temp/'
    while date < edate:
        datecode = ('%04d%02d' % (date.year, date.month))
        if datecode == '201605':
            datecode = '201505'  # use last year's data until May 2015 is released
        # Output file setup
        base_date_band_code = base[6] + '' + datecode + '_' + ('%02d' % (band))
        clipped = base_date_band_code + '_clip.tif'
        resampled = base_date_band_code + '_res.tif'

        try:
            # if I already have the needed data, save a little time
            resampled = arcpy.Raster(resampled)
        except:
            # this is the first time I'm doing these calculations
            rpath = nldas_path + base + datecode + '.002.grb'
            print rpath

            #Output to new format
            dst_filename = arcpy.env.workspace + datecode + '.tif'
            os.system("gdal_translate -of GTiff -b %d " % band + rpath + " " +
                      dst_filename)

            lowres = arcpy.Raster(dst_filename)
            print 'Clipping...'
            arcpy.Clip_management(lowres, clip_bbox, clipped, '#', '#', 'NONE')
            print 'Resampling...'
            arcpy.Resample_management(clipped, resampled, res_cellsz,
                                      resampling_method)

        print 'Zonal statistics...'
        table = 'in_memory/' + site_id
        arcpy.sa.ZonalStatisticsAsTable(a_basin, "BasinID", resampled, table,
                                        "NODATA", "MEAN")

        # Get value from table
        with arcpy.da.SearchCursor(table, ['MEAN']) as tcur:
            for val in tcur:
                ts.append(float(val[0]))
                dates.append(int(datecode))
        date = date + relativedelta(months=+1)
        table = None
    print ts
    print dates
    arcpy.env.workspace = oldws
    return numpy.asarray(ts), numpy.asarray(dates)
Exemple #30
0
def rst_resampling(inRst, outRst, outCell, template=None, technique=None):
    """
    Change the spatial resolution of your raster dataset and set rules for
    aggregating or interpolating values across the new pixel sizes.
    
    technique options:
    * NEAREST
    * MAJORITY
    * BILINEAR
    * CUBIC
    """

    import os
    from glass.pys import obj_to_lst

    inRst = obj_to_lst(inRst)

    # Get outputs
    outRst = obj_to_lst(outRst)

    if len(inRst) != len(outRst):
        from glass.pys.oss import get_filename

        OUT_FOLDER = outRst[0] if os.path.isdir(outRst[0]) else \
            os.path.dirname(outRst[0]) if os.path.isfile(outRst[0]) else \
            None

        if not OUT_FOLDER:
            raise ValueError('outRst value is not valid')

        outRst = [
            os.path.join(OUT_FOLDER,
                         get_filename(i) + '.tif') for i in inRst
        ]

        for i in range(len(inRst)):
            if inRst[i] == outRst[i]:
                outRst[i] = os.path.join(
                    OUT_FOLDER, "res_{}.tif".format(get_filename(outRst[i])))

    if template:
        tempEnvironment0 = arcpy.env.extent
        arcpy.env.extent = template

    technique = "NEAREST" if not technique else technique

    CELLSIZE = "{a} {a}".format(a=str(outCell))
    for i in range(len(inRst)):
        arcpy.Resample_management(inRst[i], outRst[i], CELLSIZE, technique)

    if template:
        arcpy.env.extent = tempEnvironment0

    return outRst