Exemple #1
0
	def reproject(self, new_workspace, name=None):
		# Project the layer from NAD 1983 to WGS 1984
		if not os.path.exists(new_workspace):
			self.createWorkspace(new_workspace)
		if new_workspace==self.getWorkspace() and name==None:
			raise Exception('Error: Cannot overwrite. Specify a new workspace or a new layer name.')
		arcpy.env.overwriteOutput = True
		transform_method = "WGS_1984_(ITRF00)_To_NAD_1983"
		output_proj = "GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
		print "Reprojecting {}...".format(self.getFilter()),
		for layer in self.scan_for_layers():
			if name==None:
				if '.tif' in os.path.basename(layer):
					arcpy.ProjectRaster_management(layer, os.path.join(new_workspace, os.path.basename(layer)), output_proj, "", "", transform_method, "", "")
				else:
					arcpy.Project_management(layer, os.path.join(new_workspace, os.path.basename(layer)), output_proj, transform_method, "", "NO_PRESERVE_SHAPE", "","NO_VERTICAL")
			else:
				if '.tif' in os.path.basename(layer):
					arcpy.ProjectRaster_management(layer, os.path.join(new_workspace, os.path.basename(layer)), output_proj, "", "", transform_method, "", "")
				else:
					arcpy.Project_management(layer, os.path.join(new_workspace, name), output_proj, transform_method, "", "NO_PRESERVE_SHAPE", "","NO_VERTICAL")
				self._filter = name
				break
		self._workspace = new_workspace
		print "Done"
Exemple #2
0
def get_zodgn(lon,lat):
    rectangle = zod_envelope(lon,lat)
    if abs(lat)<71:
        if abs(lon)<90: arcpy.Clip_management(zodraster,rectangle,"zodclip.tif")
        else: arcpy.Clip_management(zodraster1, rectangle, "zodclip.tif")
        lon = (lon+90) % 180 - 90
        p = [tc(lon,lat),"BILINEAR", "6000"]
        arcpy.ProjectRaster_management("zodclip.tif", "zodgn.tif", *p)
    else: 
        p = [tc(lon,lat),"BILINEAR", "6000"]
        arcpy.ProjectRaster_management(zodraster, "zodtemp.tif", *p)
        arcpy.Clip_management('zodtemp.tif', rectangle, 'zodgn.tif')
Exemple #3
0
def webProducts(rast,
                project=True,
                method="POINT_REMOVE",
                tolerance=15,
                minimumArea=3000):
    rastName = arcpy.Describe(rast).baseName
    if project:
        arcpy.ProjectRaster_management(
            rastName, "WEB" + rastName,
            r"Coordinate Systems/Projected Coordinate Systems/World/WGS 1984 Web Mercator (Auxiliary Sphere).prj",
            "BILINEAR", "", "NAD_1983_to_WGS_1984_5")
        raster = "WEB" + rastName
    q = arcpy.RasterDomain_3d(raster, raster + "q", "POLYGON")
    qq = arcpy.Union_analysis(q, raster + "qq", "ALL", 0.1, "NO_GAPS")
    qqq = arcpy.Dissolve_management(qq, raster + "qqq")
    qqqq = arcpy.cartography.SimplifyPolygon(qqq, raster + "qqqq", method,
                                             tolerance, minimumArea,
                                             "NO_CHECK", "NO_KEEP")
    arcpy.Buffer_analysis(qqqq, "out_" + raster, "30 Feet", "FULL", "", "NONE")
    print "Products created."

    arcpy.Delete_management(rast)
    arcpy.Delete_management(raster + "q")
    arcpy.Delete_management(raster + "qq")
    arcpy.Delete_management(raster + "qqq")
    arcpy.Delete_management(raster + "qqqq")
Exemple #4
0
def renamePRISMImagery(prism_variable, temporal_range):
	try:
		outputFolder = "H:/PRISM/4km/" + prism_variable + "/" + temporal_range + "/az/4km"
		
		# iterate through each of the year range folders
		dateRangeFolder = "H:/PRISM/4km/" + prism_variable + "/" + temporal_range + "/az"
		
		env.workspace = dateRangeFolder
		
		for root, dirs, files in os.walk(dateRangeFolder):	
			for file in files:
				print(file)
				fileNameArray = file.split(".")
				if(fileNameArray[2] == 'tif' and len(fileNameArray) == 3):
					sourceFileName = dateRangeFolder + "/" + fileNameArray[0] + "." + fileNameArray[1] + ".tif"
					azFileName = outputFolder + "/" + str(fileNameArray[0]).replace("us", "az") + "." + fileNameArray[1] + ".tif"
					print(azFileName)
					# define the image spatial reference for the US image
					arcpy.ProjectRaster_management(sourceFileName,azFileName,wgs84z12_cs,"NEAREST",4307.10933863036,"","","")

		print("All Done!")
	except:
		print("*** Error ***")
		print(sys.exc_info()[0])
		print(sys.exc_info()[1])
		print(sys.exc_info()[2])
Exemple #5
0
def clipByPoly(inPoly, inraster, outdir, topo=False):
    """takes a polygon and clips the inraster to its extent and places output in the outdir"""
    # get the raster description
    try:
        rasterDesc = arcpy.Describe(inraster)
    except Exception as e:
        print e, inraster, 'here'
        return None
    # so we can get the spatialReference of the raster
    rasterSpref = rasterDesc.spatialReference
    # and also the extent of the raster
    rasterExtent = rasterDesc.extent.projectAs(inPoly.spatialReference)
    # if it is a topo
    if topo:
        # then we use the extent without a shift because we know it is good already
        rawutmextent = inPoly.extent
    # otherwise it is for a photo or something else and we dont know that the extent is already matched up
    else:
        # use the shiftExtents function to move the clip extent to be within the raster extent
        rawutmextent = shiftExtents(inPoly.extent, rasterExtent)
    # format the extent object for clipping

    utmextent = ' '.join(
        map(str, (rawutmextent.XMin, rawutmextent.YMin, rawutmextent.XMax,
                  rawutmextent.YMax)))
    # project the clip extent into the spatialReference of the raster
    rawextent = inPoly.projectAs(rasterSpref).extent
    # and reformat that as well
    extent = ' '.join(
        map(str,
            (rawextent.XMin, rawextent.YMin, rawextent.XMax, rawextent.YMax)))
    if rasterExtent.disjoint(extentToArcPolygon(rawutmextent)):
        print 'this is stupid'
        return None

    # create the output name
    # note that we are using tif so this actually works
    outName = os.path.join(outdir, os.path.split(inraster)[1][:-4] + '.tif')
    # do the initial clip to get the potion of the raster that we need
    arcpy.Clip_management(inraster, extent, outName, "", "", 'NONE')
    # if the raster spatial reference is the same as the output we can exit the function right now
    if rasterSpref == inPoly.spatialReference:
        return True
    # create a name for a temp file
    reprojectName = outName[:-4] + 'reproject' + outName[-4:]
    # this part can fail so we put it in a try clause
    # seems like most of the failures were caused by a lock, so these are not a huge issue but should still be in the try block
    try:
        # project the clipped raster into the correct UTM
        arcpy.ProjectRaster_management(outName, reprojectName, inPoly)
        # delete the original clip
        arcpy.Delete_management(outName)
        # reclip the reprojected raster
        arcpy.Clip_management(reprojectName, utmextent, outName, "", "",
                              'NONE')
        # and delete the reprojected unclipped raster
        arcpy.Delete_management(reprojectName)
    except Exception as e:
        print e, outName
    return True
Exemple #6
0
 def reshape(in_path, out_path, name, resamp_type, dem_specs, cell_size,
             proj, tmp_dir, roi_layers):
     print('Prepping ' + name + ' ...')
     arcpy.env.snapRaster = dem_specs.dem
     file_in = str(in_path)
     # buff = tmp_dir + '/buff_{}.tif'.format(name)
     buff = tmp_dir + '/buff.tif'
     reproj = tmp_dir + '/reproj.tif'
     file_out = str(out_path)
     arcpy.Clip_management(in_raster=file_in,
                           out_raster=buff,
                           in_template_dataset=roi_layers.roi_buff,
                           clipping_geometry=True)
     arcpy.ProjectRaster_management(in_raster=buff,
                                    out_raster=reproj,
                                    out_coor_system=proj,
                                    resampling_type=resamp_type,
                                    cell_size=cell_size)
     envelope = '{} {} {} {}'.format(dem_specs.extent.XMin,
                                     dem_specs.extent.YMin,
                                     dem_specs.extent.XMax,
                                     dem_specs.extent.YMax)
     arcpy.Clip_management(in_raster=reproj,
                           out_raster=file_out,
                           rectangle=envelope,
                           nodata_value=-9999)
     print('Done')
Exemple #7
0
def arcReprojectData(fileList,outCRS):
	import arcpy
	import re 
	import os
	from time import gmtime, strftime
	os.mkdir("prjdata")
	with open("prjdata\CRSmeta",'w') as meta: 
		meta.write(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
		meta.write("\n Coordinate Reference System \n")
	for f in fileList:
		# remove file extensions
		ext = re.match(".*(\..*)",f) 
		print(ext)
		if m != None: 
			data = f[:len(ext.group(1))] 
		else: 
			data = f
			
		# run the reprojection tool
		try:
			if ext=='.shp': arcpy.Project_management(data,"prjdata/"+data,outCRS)
			if ext!='.shp': arcpy.ProjectRaster_management(data,"prjdata/"+data,outCRS)
			# print messages when the tool runs successfully
			print(arcpy.GetMessages(0))
			meta.write(arcpy.GetMessages(0))
		except arcpy.ExecuteError:
			print(arcpy.GetMessages(2))
			meta.write(arcpy.GetMessages(0))
		except Exception as ex:
			print(ex.args[0])
			meta.write(arcpy.GetMessages(0))
Exemple #8
0
def ProjectRaster(workDir, inRaster,out_coor_system):
    # Name: Project_Raster.py
    # Description: Converts a raster dateset to different coordinate system.
    # Requirement: None
    # Input: working Dir, r"c:\work\path\to\dir\"
    #        inRaster filename
    #        output filename
    #        in_coor_system
    #        out_coor_system
    #        sampling algorithm
    # Output: inRaster_reproject+'.tiff'
    # Dr. Liang Kuang, 2016/02/26

    #Import system modules
    from os import path
    import arcpy
    from arcpy import env
    
	#proj = arcpy.SpatialReference(4326)  #WGS1984

    # Set environment settings
    env.workspace = workDir
    print(workDir)
    #env.workspace = r"R:\Projects\ESTOFS_for_Micronesia\Data\Bathymetry\ngdc_bathy\BAG\NorthernMarianas"

    # Set local variables
    #inRaster = "W00157_MB_8m_MLLW_Combined1.tif"
    strList = inRaster.split('.')
    outRaster = strList[0] + '_reproject.tiff' 
    print(outRaster)
    # Reproject a Raster image to different projection
    #arcpy.ProjectRaster_management(inRaster,outRaster,out_coor_system,sample_alg,"#","#","#","#")
    arcpy.ProjectRaster_management(inRaster,outRaster,out_coor_system)
    print('Projection done!')
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 ExtractCover(xinfo, file='', name='', dtype='', units='', description=''):
    """extract land cover raster"""
    # then aggregate as part of reprojection
    info = ReadYaml(xinfo['yaml'])
    arcpy.env.snapraster = info['refraster']
    prjrast = file + 'p'
    clip = os.path.join(info['outpath'], name)

    arcpy.ProjectRaster_management(file,
                                   prjrast,
                                   info['refraster'],
                                   'MAJORITY',
                                   cell_size=info['cellsize'])
    outExtractByMask = arcpy.sa.ExtractByMask(prjrast, info['refraster'])
    outExtractByMask.save(clip)

    # create netcdf variable
    dev = arcpy.RasterToNumPyArray(clip)
    rootgrp = Dataset(info['netcdf'], 'a')
    lc = rootgrp.createVariable(name,
                                dtype, ('t', 'x', 'y'),
                                fill_value=missvals[dtype])
    lc.description = description
    lc.units = units
    for i, t in enumerate(info['tcoords']):
        lc[i, :, :] = dev

    rootgrp.close()
    WriteYaml(info)
    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 Raster_to_Contour():
    #Set up working environment
    arcpy.env.workspace = r"C:\GIS Automation\Florida Project\data"

    #Reproject Raster
    arcpy.ProjectRaster_management(
        "03meter_smoothed.tif", "03meter_smoothed_reproject.tif",
        "NAD 1983 StatePlane Florida East FIPS 0901 (US Feet).prj", "NEAREST")

    #Build pyramids for Raster
    #arcpy.BuildPyramids_management("f19_resample_2_reproject.tif", "-1", "NONE", "NEAREST", "NONE", "75")

    #Convert Raster unit from meter to feet
    outRas = Raster("03meter_smoothed_reproject.tif") * 3.28
    outRas.save("03meter_smoothed_feet.tif")

    #Extract Contours
    arcpy.sa.Contour("03meter_smoothed_feet.tif", "contours_feet_1.shp", 1, 0)

    #Export to CAD
    input_feature = "contours_feet_1.shp"
    output_type = "DWG_R2013"
    output_file = "Contours_feet_1_crash.dwg"
    try:
        arcpy.ExportCAD_conversion(input_feature, output_type, output_file)

    except:
        print arcpy.GetMessages()
Exemple #13
0
def ProjectToMatch_ras(in_Data, in_Template, out_Data, resampleType="NEAREST"):
    '''Check if input raster and template raster have same spatial reference.
   If not, reproject input to match template.
   Parameters:
   in_Data = input raster to be reprojected
   in_Template = dataset used to determine desired spatial reference and cell alignment
   out_Data = output raster resulting from resampling
   resampleType = type of resampling to use (NEAREST, MAJORITY, BILINEAR, or CUBIC)
   '''

    # Compare the spatial references of input and template data
    (sr_In, sr_Out, reproject, transform,
     geoTrans) = CompareSpatialRef(in_Data, in_Template)

    if reproject == 0:
        printMsg(
            'Coordinate systems for input and template data are the same. No need to reproject.'
        )
        return in_Data
    else:
        printMsg('Reprojecting input raster to match template...')
        arcpy.env.snapRaster = in_Template
        if transform == 0:
            printMsg('No geographic transformation needed...')
        else:
            printMsg('Applying an appropriate geographic transformation...')
        arcpy.ProjectRaster_management(in_Data, out_Data, sr_Out, resampleType,
                                       "", geoTrans)
        return out_Data
    def execute(self, parameters, messages):
        """The source code of your tool."""
        arcpy.env.overwriteOutput = True

        arcpy.AddMessage("Reproject a directory of rasters into a consistent projection")

        for param in parameters:
            arcpy.AddMessage("Parameter: %s = %s" % (param.name, param.valueAsText) )

        input_directory = parameters[0].valueAsText
        output_directory = parameters[1].valueAsText
        coordinate_system = parameters[2].valueAsText

        # Set environment settings
        env.workspace = input_directory
        rasterlist = arcpy.ListRasters("*")
        arcpy.AddMessage("There are " + str(len(rasterlist)) + " rasters to process.")
        if not os.path.exists(output_directory):
            os.makedirs(output_directory)

        for raster in rasterlist:

            arcpy.AddMessage("Reprojecting " + str(raster) + ".")
            arcpy.ProjectRaster_management(raster, os.path.join(output_directory,raster),
                                           coordinate_system,"NEAREST","#","#","#","#")
        return
def HSMask(year_day, clipshp, rastband, Sun_azi, Sun_elev, Asia_DEM, prj): 
    """Clips a subset of a larger DEM, and then creates both a hillshade and a shadow mask. Returns the shadow mask, 
    as well as a projected version of the DEM"""
    outDEM = Path_SRTM + year_day + "_DEM.tif"  
    HSname = Path_SRTM + year_day + "_DEM_HS.tif"
   
    arcpy.env.snapRaster = Asia_SRTM
    arcpy.env.extent = clipshp
    
    SRTM_DEM_clip = arcpy.sa.ExtractByMask(Asia_DEM, clipshp)
    SRTM_DEM_clip.save(outDEM)

    prjDEM = Path_SRTM + year_day + "_DEM_prj.tif"
    arcpy.ProjectRaster_management(outDEM, prjDEM, prj, 'BILINEAR', '30')
    arcpy.Delete_management(outDEM)
    
    HS = arcpy.sa.Hillshade(prjDEM, Sun_azi, Sun_elev, "SHADOWS") #Create Hillshade image
    HS.save(HSname)
    del HS
    
    #Find shadowed areas and return a binary raster to use as a mask 
    HS_Maskout = Path_SRTM + year_day + "_HSMask.tif" 
    HS_Mask = arcpy.sa.Con(HSname, 1, 0, '"VALUE" < 10')
    HS_Mask.save(HS_Maskout)
    del HS_Mask
    arcpy.Delete_management(HSname)
    
    return HS_Maskout, prjDEM
Exemple #16
0
def reprojectGeoDEM(inputDEM, outputDEM):

    from LUCI_SEEA.lib.external import utm

    log.info("DEM has geographic coordinate system. Reprojecting...")

    DEMSpatRef = arcpy.Describe(inputDEM).SpatialReference
    DEMExtent = arcpy.Describe(inputDEM).extent

    # Find midpoint of raster
    midPointX = DEMExtent.XMin + (DEMExtent.XMax - DEMExtent.XMin) / 2
    midPointY = DEMExtent.YMin + (DEMExtent.YMax - DEMExtent.YMin) / 2

    # Find out which UTM zone the DEM should be projected to
    northing, easting, zone, letter = utm.from_latlon(midPointY, midPointX)
    if letter >= "N":
        northSouth = "N"
    else:
        northSouth = "S"

    # Create the new projected coordinate system
    projSpatRef = arcpy.SpatialReference("WGS 1984 UTM Zone " + str(zone) + northSouth)

    # Obtain the transformation string to transform from GCS to PCS
    transformation = arcpy.ListTransformations(DEMSpatRef, projSpatRef, DEMExtent)[0]

    # Reproject DEM to Projected Coord System
    arcpy.ProjectRaster_management(inputDEMRaster, outputDEM, projSpatRef, geographic_transform=transformation)

    # Update coord system
    DEMSpatRef = arcpy.Describe(outputDEM).SpatialReference
    log.info("DEM coordinate system is now " + DEMSpatRef.Name)
Exemple #17
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 #18
0
def Project_raster(rasterfile, newfile_name, coord_system=4326):
    sr = arcpy.SpatialReference(coord_system)
    new_rasterfile = rasterfile.name
    #if os.path.isfile(new_rasterfile):
    #   arcpy.Delete_management(new_rasterfile)
    arcpy.ProjectRaster_management(rasterfile, new_rasterfile, sr)
    new_rasterfile1 = arcpy.Raster(new_rasterfile)
    return new_rasterfile1
def projectRasters(in_ws, out_coords, out_ws):
    env.workspace = in_ws
    env.overwriteOutput = True
    in_rasters = arcpy.ListRasters()
    for raster in in_rasters:
        print "Projecting", raster, os.path.join(out_ws, raster)
        arcpy.ProjectRaster_management(raster, os.path.join(out_ws, raster),
                                       out_coords)
Exemple #20
0
def get_galgn(lon, lat):
    rectangle = gal_envelope(lon, lat)
    if abs(lat) < 71:
        if abs(lon) < 90:
            arcpy.Clip_management(galraster, rectangle, "galclip.tif")
        else:
            arcpy.Clip_management(galraster1, rectangle, "galclip.tif")
        lon = (lon + 90) % 180 - 90
        p = [tc(lon, lat), "BILINEAR", "6000"]
        arcpy.ProjectRaster_management("galclip.tif", "galgn.tif", *p)
    else:
        p = [tc(lon, lat), "BILINEAR", "6000"]
        if lat >= 71:
            arcpy.ProjectRaster_management(galrastern, "galtemp.tif", *p)
        else:
            arcpy.ProjectRaster_management(galrasters, "galtemp.tif", *p)
        arcpy.Clip_management('galtemp.tif', rectangle, 'galgn.tif')
def arcReprojectBatch(wd, fileList, outCRS=None):
    import os, glob, re, sys, arcpy
    from time import gmtime, strftime
    arcpy.env.workspace = wd
    if type(fileList) is not list:
        print(arcReprojectBatch.__name__ +
              "failed, fileList must be of type list")
        sys.exit(arcReprojectBatch.__name__ +
                 "failed, fileList must be of type list")

    if outCRS is None: ourCRS = arcpy.SpatialReference(26918)  #NAD83 UTM 18N

    outDir = "\\prjbatch" + strftime('%Y%m%d%H%M%S', gmtime()) + "\\"
    os.mkdir(arcpy.env.workspace + outDir)
    outPath = arcpy.env.workspace + outDir
    print(outPath)

    # write metadata
    meta = open(outPath + "CRSmeta", 'w')
    meta.write(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
    meta.write("\n Coordinate Reference System \n")

    for f in fileList:
        # remove file extensions
        m = re.match(".*(\..*)", f)
        if m == None:
            ext = ""
            data = f
        else:
            ext = m.group(1)
            data = f[:(len(f) - len(ext))]
        print(data, ext)

        # run the reprojection tool
        try:
            print("trying to reproject data")
            if ext == '.shp':
                out = arcpy.Project_management(wd + f, outPath + f, outCRS)
            if ext != '.shp':
                out = arcpy.ProjectRaster_management(wd + f, outPath + f,
                                                     outCRS)
            # print messages when the tool runs successfully
            del out
            print(arcpy.GetMessages(0))
            meta.write(arcpy.GetMessages(0))

        except arcpy.ExecuteError:
            print(arcpy.GetMessages(2))
            meta.write(arcpy.GetMessages(0))
        except Exception as ex:
            print(ex.args[0])
            meta.write(arcpy.GetMessages(0))

        mxd = arcpy.mapping.MapDocument(r"C:\Temp\ArcGIS\Untitled.mxd")
        for df in arcpy.mapping.ListDataFrames(mxd):
            for lyr in arcpy.mapping.ListLayers(mxd, "", df):
                #if lyr.name.lower() == "rivers":
                arcpy.mapping.RemoveLayer(df, lyr)
def land_use(nlcd_layer, search_area, excluded_types, tiger_lines,
             census_places, crs, workspace):
    arcpy.CheckOutExtension("spatial")

    geoprocessing_log.info("Extracting NLCD raster to search area")
    nlcd_in_area = arcpy.sa.ExtractByMask(nlcd_layer, search_area)
    avoid_types = [exclude.value for exclude in excluded_types]

    thresholded_raster = nlcd_in_area
    for avoid in avoid_types:  # this is inefficient, but I couldn't get it to work with a "not in" and I need something that works for n number of values
        thresholded_raster = arcpy.sa.Con(thresholded_raster != avoid,
                                          thresholded_raster, 0)

    scratch_raster = generate_gdb_filename("temp_raster", scratch=True)
    thresholded_raster.save(
        scratch_raster)  # save it so we can use it for environment variables

    stored_environments = store_environments(
        ('cellSize', 'mask', 'extent', 'snapRaster')
    )  # cache the env vars so we can reset them at the end of this function
    arcpy.env.cellSize = scratch_raster
    arcpy.env.mask = scratch_raster
    arcpy.env.extent = scratch_raster
    arcpy.env.snapRaster = scratch_raster

    roads_mask = make_road_mask(tiger_lines,
                                census_places=census_places,
                                search_area=search_area)
    roads_raster = generate_gdb_filename("roads_raster")
    geoprocessing_log.info("Converting roads mask to raster")
    try:
        arcpy.PolygonToRaster_conversion(roads_mask, "OBJECTID", roads_raster)
        #arcpy.CalculateStatistics_management(roads_raster)  # crashes for invalid statistics unless we run this after the conversion
    except:
        geoprocessing_log.error(
            "Error creating raster: {0:s} - from roads mask: {1:s}".format(
                roads_raster, roads_mask))
        raise

    # Raster Calculations
    final_nlcd = arcpy.sa.Con(arcpy.sa.IsNull(arcpy.sa.Raster(roads_raster)),
                              thresholded_raster, 1)
    intermediate_raster = generate_gdb_filename("intermediate_nlcd_mask")
    projected_raster = generate_gdb_filename("projected_nlcd_mask",
                                             gdb=workspace)
    final_nlcd.save(intermediate_raster)

    reset_environments(stored_environments)

    geoprocessing_log.info("Reprojecting final raster")
    arcpy.ProjectRaster_management(intermediate_raster,
                                   projected_raster,
                                   out_coor_system=crs)

    filtered_nlcd_poly = filter_patches.convert_and_filter_by_code(
        projected_raster, filter_value=0)

    return filtered_nlcd_poly
 def _reproject_raster(self, current_ref, target_ref, file_path):
     """ Reproject raster """
     file_name = ntpath.basename(file_path)
     proj_out_ras = self.dest_dir + '/PROJ_' + file_name
     print('Projecting..... {0} from {1} to {2}'.format(
         file_name, current_ref.name, target_ref.name))
     arcpy.ProjectRaster_management(file_path, proj_out_ras, target_ref, '',
                                    '', '', '', current_ref)
     return proj_out_ras
Exemple #24
0
def project (rasters, cds):
    
    outrasters = []
    for raster in rasters:
        outraster = raster[:-4]+'_proj.tif'
        arcpy.ProjectRaster_management(raster, outraster, arcpy.SpatialReference(cds))
        outrasters.append(outraster)
        
    return outrasters
Exemple #25
0
def reproject(input_dir, output_dir, projection, meta):
    ''' Reproject raster band

        @param   input_dir: landsat 8 directory after unzip
        @type    input_dir: c{str}
        @param   meta: metadata parsed from MTL file
        @type    meta: dictionary
        @return  output_dir: output directory path
    '''

    ##    ##  Setting output directory id not defined
    ##
    ##    if output_dir is None:
    ##        output_dir = os.path.join(input_dir, "processed")
    ##        if os.path.exists(output_dir):
    ##            sys.exit(0)
    ##            print "\nDirectory for reprojection already Exisits"
    ##        else:
    ##            os.mkdir(output_dir)
    ##            print "\nCreated the output directory: " + output_dir
    ##    else:
    ##        if os.path.exists(output_dir):
    ##            sys.exit(0)
    ##            print "\nDirectory for reprojection already Exisits"
    ##        else:
    ##            os.mkdir(output_dir)
    ##            print "\nCreated the output directory: " + output_dir

    ap.env.workspace = input_dir

    rasters = ap.ListRasters('*.TIF')
    ms_bands = [band for band in rasters if (band_nmbr(band) != None)]
    bqa_band = [band for band in rasters if (band_nmbr(band) == None)][0]

    try:
        checkout_Ext("Spatial")
        print "\nReprojecting and Cleaning landsat bands."
        ap.AddMessage("\nReprojecting and Cleaning landsat bands.")
        for band in ms_bands:
            print "\nReclassifying NoData for band " + band
            ap.AddMessage("\nReclassifying NoData for band " + band)
            outCon = ap.sa.Con(ap.sa.Raster(bqa_band) != 1, ap.sa.Raster(band))
            out_band = os.path.join(output_dir, band)

            print "Reprojecting band"
            ap.AddMessage("Reprojecting band")
            ap.ProjectRaster_management(outCon, out_band, projection)

    except SpatialRefProjError:
        ap.AddError(
            "Spatial Data must use a projected coordinate system to run")

    except LicenseError:
        ap.AddError("Spatial Analyst license is unavailable")

    finally:
        checkin_Ext("Spatial")
Exemple #26
0
def mosaic():
    global nhdsubregion

    # Select the right HUC4 from WBD_HU4 and make it it's own layer.
    arcpy.MakeFeatureLayer_management("WBD_HU4", "HU4")
    field = "HUC_4"
    where = '"' + field + '" = ' + "'" + str(nhdsubregion) + "'"
    arcpy.SelectLayerByAttribute_management("HU4", "NEW_SELECTION", where)
    arcpy.CopyFeatures_management("HU4", "Subregion")

    # Apply a 5000 meter buffer around subregion
    arcpy.Buffer_analysis("Subregion", "Subregion_5000m_buffer", "5000 meters")
    arcpy.AddMessage("Buffered subregion.")

    # Naming conventions for mosaic output file
    subregion_number = os.path.basename(nhd)
    nhdsubregion = subregion_number[4:8]

    # Walk through the folder with NEDs to make a list of rasters
    mosaicrasters = []
    for dirpath, dirnames, filenames in arcpy.da.Walk(
            nedfolder, datatype="RasterDataset"):
        for filename in filenames:
            name = os.path.join(dirpath, filename)
            mosaicrasters.append(name)

    arcpy.AddMessage("Found NED ArcGrids.")

    # Mosaic, clip and then project to USGS Albers
    arcpy.MosaicToNewRaster_management(mosaicrasters, outfolder,
                                       "mosaicNAD.tif", nad83, "32_BIT_FLOAT",
                                       "", "1", "LAST")
    arcpy.Clip_management(
        outfolder + "\\" + "mosaicNAD.tif", '',
        outfolder + "\\" + "tempNED13_" + nhdsubregion + ".tif",
        "Subregion_5000m_buffer", "0", "ClippingGeometry")
    tempned13 = os.path.join(outfolder, "tempNED13_" + nhdsubregion + ".tif")
    arcpy.ProjectRaster_management(
        tempned13, os.path.join(mosaicfolder,
                                "NED13_" + nhdsubregion + ".tif"), albers,
        "BILINEAR", "10", "", "", nad83)
    arcpy.AddMessage("Mosaiced, clipped and projected NED tiles.")

    # Variables for intermediate data
    MosaicNAD = os.path.join(outfolder, "mosaicNAD.tif")
    MosaicClip = outfolder + "\\" + "tempNED13_" + nhdsubregion + ".tif"
    subregion_ned = outfolder + "\\" + "mosaic" + nhdsubregion + "\\" + "NED13_" + nhdsubregion + ".tif"
    global subregion_ned

    # Clean up
    arcpy.Delete_management(MosaicNAD)
    arcpy.Delete_management(MosaicClip)
    arcpy.Delete_management("Subregion")
    arcpy.Delete_management("Subregion_5000m_buffer")
    arcpy.AddMessage(
        "Cleaned up intermediate data from mosaic tool. Mosaic done.")
    return
Exemple #27
0
def DTE(tiffile):

    ##  Retrieve country ISO:
    iso = tiffile.split("/")[3].split("\\")[0]
    print("Working on {0}".format(iso))
    ##  Set the output path:
    outpath = tiffile.split(os.path.basename(tiffile))[0]

    print("\tProjecting Data...")
    ##  Project the dataset  ##
    ##    Retrieve projection from dictionary:
    intermediate_prj = prj_dict[iso]

    ##    Set the ouput data name:
    outpath = ensure_dir(tiffile.split(".tif")[0] + "tmp/")
    output = outpath + "_projected.tif"

    ##    Project the dataset:
    data_desc = arcpy.Describe(tiffile)
    input_prj = data_desc.SpatialReference.exportToString()
    arcpy.ProjectRaster_management(tiffile, output, intermediate_prj,
                                   "NEAREST", "100", "#", "#", input_prj)

    ##  Retrieve the projected dataset:
    prjtif = output

    print("\tPolygonizing...")
    ##  Calculate the DTE  ##
    ##    Raster to Polygon:
    arcpy.RasterToPolygon_conversion(prjtif, "D:/tmp/" + iso + "_polyras.shp",
                                     "NO_SIMPLIFY", "VALUE")
    polyras = "D:/tmp/" + iso + "_polyras.shp"

    ##    Convert the polygon to a feature layer:
    polyfeat = arcpy.MakeFeatureLayer_management(polyras, "polyras")

    print("\tLinizing...")
    ##    Polygon to Line:
    arcpy.PolygonToLine_management(polyfeat, "D:/tmp/" + iso + "_polyline.shp",
                                   "IGNORE_NEIGHBORS")
    polyline = "D:/tmp/" + iso + "_polyline.shp"

    print("\tCalculating Distance to Line...")
    ##    Distance to Line:
    output = "D:/tmp/" + iso + "dst.tif"
    dstras = arcpy.sa.EucDistance(polyline, cell_size=100)
    dstras.save(output)

    ##    Convert the internal numbers to negative using rastermath:
    print("\tCalculating negative values...")
    outpath = ensure_dir(tiffile.split(".tif")[0] + "Output/")
    output = outpath + "_projected_DTE.tif"
    urb = arcpy.Raster(tiffile)
    dteras = arcpy.sa.Con(urb == 1, -1, 0) * dstras + arcpy.sa.Con(
        urb == 0, 1, 0) * dstras
    dteras.save(output)
Exemple #28
0
 def proj_ras(self):
     """Project each raster as specified"""
     for source_path in self.get_dir_paths():
         for file in os.listdir(source_path):
             if file.startswith("africa_") & file.endswith(".tif"):  # Check if TIF file
                 file_path = os.path.join(source_path, file).replace("\\","/")
                 out_ras = "E:/Omusati_covariates/ndvi/processed_data/" + file
                 print("PROJECTING ...... " + file)
                 arcpy.ProjectRaster_management(file_path, out_ras, "PROJCS['UTM_Zone_33S',GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',15.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]", "NEAREST", "250 250", "", "", "PROJCS['Sphere_Sinusoidal',GEOGCS['GCS_Sphere',DATUM['D_Sphere',SPHEROID['Sphere',6370997.0,0.0]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Sinusoidal'],PARAMETER['false_easting',0.0],PARAMETER['false_northing',0.0],PARAMETER['central_meridian',30.0],UNIT['Meter',1.0]]")
     print("ALL RASTERS PROJECTED SUCCESSFULLY!!!!!")
Exemple #29
0
def project_batch():
    env.workspace = raster_path
    rafters = arcpy.ListRasters("*", "tif")
    for raster in rafters:
        out = "\\" + new_path_name + "\\" + "Pr_" + raster[:]
        arcpy.ProjectRaster_management(raster, out, out_coor_system, rs_type,
                                       c_size, "#", "#", "#")
        arcpy.AddMessage("Step2:Pr_" + raster[:] + "has done.")
        arcpy.SetProgressorPosition()
    arcpy.AddMessage("Step2:Completed")
Exemple #30
0
 def project_raster(path, null_raster):
     #in_Raster=os.path.join(Path,Copied_Raster_Name)
     #Read_Project_Raster=arcpy.Raster(in_Raster)
     out_projected_raster = os.path.join(
         path, projected_raster_name)
     arcpy.ProjectRaster_management(
         null_raster, out_projected_raster,
         self.projection, "BILINEAR", "#", "#", "#",
         "#")
     return out_projected_raster