Exemple #1
0
def createRC(path, rasterFile):
    import arcpy
    import os
    from arcpy import env
    env.workspace = path
    rasterFile = arcpy.RasterToGeodatabase_conversion(rasterFile, path)
    return rasterFile
def add_to_gdb(src, dest):
    switch_workspace(src)
    vector = arcpy.ListFeatureClasses()
    raster = arcpy.ListRasters()
    for fc in raster:
        arcpy.RasterToGeodatabase_conversion(fc, dest)
    for fc in vector:
        arcpy.CopyFeatures_management(fc, os.path.join(dest, fc.split('.')[0]))
    switch_workspace(src, dest)
Exemple #3
0
def addPRISMRastersToCatalog(prism_variable, time_resolution):
	try:
		env.workspace = "H:/PRISM/4km/" + prism_variable + "/" + time_resolution
		catalogName = "C:/my/GIS/PRISM/usPRISM.gdb/conus_PRISM_4km_" + time_resolution + "_tminn_RC"

		rasters = arcpy.ListRasters("*","tif")

		rasterNames = ""
		for r in rasters:
			rasterNames = rasterNames + r + ";"

		print("Adding rasters to catalog...")			
		arcpy.RasterToGeodatabase_conversion(rasterNames, catalogName)

		print("Finished adding rasters to catalog: " + catalogName)


	except:
		print("*** Error ***")
		print(sys.exc_info()[0])
		print(sys.exc_info()[1])
		print(sys.exc_info()[2])
Exemple #4
0
from arcpy import env
arcpy.env.overwriteOutput = True
arcpy.CheckOutExtension("spatial")

#working directory
baseRoot = r"D:\PROJECTS\NEON_D17\ANALYSIS\EXPORT\RASTER\SOLAR\monthly_solar_splitter"
arcpy.env.workspace = baseRoot
print "The root directory for this project is set to: " + str(baseRoot)

nameGDB = "TEAK_SOLAR_HALF_MONTHS_2013_Buffered150m"
inRaster = r"D:\PROJECTS\NEON_D17\ANALYSIS\EXPORT\RASTER\DSM\TEAK_DSM_1m.tif"

outGDB = arcpy.CreateFileGDB_management(baseRoot, nameGDB, "CURRENT")
arcpy.env.workspace = str(outGDB)
print "Adding... " + inRaster + " to: Geodatabase = " + nameGDB + "..."
inRaster = arcpy.RasterToGeodatabase_conversion(inRaster, outGDB, "")
rasterList = arcpy.ListRasters()
inRasterName = rasterList[0]
inRaster = str(inRaster) + "\\" + str(inRasterName)
latitude = "36.5"  #approx latitude
skySize = "200"
year = "2013"

#Define the moths/quarters
monthParameters = [
    "MultiDays   " + year + "    1   15", "MultiDays   " + year +
    "    16   31", "MultiDays   " + year + "    32   45", "MultiDays   " +
    year + "    46   59", "MultiDays   " + year + "    60   75",
    "MultiDays   " + year + "    76   90", "MultiDays   " + year +
    "    91   105", "MultiDays   " + year + "    106   120", "MultiDays   " +
    year + "    121   136", "MultiDays   " + year + "    137   151",
    for i in zipped_data:
        row = rows.newRow()
        row.setValue(table_field_name1, i[0])
        row.setValue(table_field_name2, i[1])
        row.setValue(table_field_name3, i[2])
        row.setValue(table_field_name4, i[3])
        row.setValue(table_field_name5, i[4])
        row.setValue(table_field_name6, i[5])
        row.setValue(table_field_name7, i[6])
        rows.insertRow(row)
    del row
    del rows

    # Export files to new geodatabase
    arcpy.FeatureClassToGeodatabase_conversion(polygon_name, output_gdb_path)
    arcpy.RasterToGeodatabase_conversion(depth_grid_name, output_gdb_path)
    arcpy.TableToGeodatabase_conversion(table_name, output_gdb_path)

    # Delete files from workspace
    arcpy.Delete_management(polygon_name)
    arcpy.Delete_management(table_name)
    arcpy.Delete_management(depth_grid_name)

    #Delete temporary files and variables
    if delete_intermediate_data == True:
        arcpy.AddMessage("Deleting temporary files for {0}".format(stage))
        arcpy.Delete_management(TIN)
        del TIN
        arcpy.Delete_management(RasterFromTIN)
        del RasterFromTIN
        arcpy.Delete_management(Subtracted)
Exemple #6
0
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      MMoore
#
# Created:     14/06/2018
# Copyright:   (c) MMoore 2018
# Licence:     <your licence>
#-------------------------------------------------------------------------------

import arcpy, urllib, urllib2, requests
import os, time
from os import listdir
from os.path import isfile, join
from arcpy import env
from arcpy.sa import *
import shutil, sys

arcpy.env.overwriteOutput = True

image_folder = r'W:\Heritage\Heritage_Projects\1495_PlantConservationPlan\BONAP\test\bonap_originals'
image_gdb = 'W:\Heritage\Heritage_Projects\1495_PlantConservationPlan\bonap\test\bonap_rasters.gdb'

bonap_maps = [f for f in os.listdir(image_folder) if f.endswith('.png')]
bonap_maps = [os.path.join(image_folder,f) for f in bonap_maps]

arcpy.RasterToGeodatabase_conversion(bonap_maps, image_gdb)
Exemple #7
0
        PercentArea = [
            row[0] for row in arcpy.da.SearchCursor(
                "{0}_Hypsometry".format(reach), "Percent_Area")
        ]
        with arcpy.da.UpdateCursor(
                "hypsometry_all",
            ["{0}_Percent_Area".format(reach)]) as cursor:
            n = 0
            for row in cursor:
                row[0] = PercentArea[n]
                cursor.updateRow(row)
                n += 1

# Export files to new geodatabase
arcpy.TableToGeodatabase_conversion("Hypsometry_all", output_gdb_path)
arcpy.RasterToGeodatabase_conversion(depth_grid_name, output_gdb_path)
arcpy.RasterToGeodatabase_conversion("Hypsometry", output_gdb_path)
for reach in reach_list:
    arcpy.RasterToGeodatabase_conversion("{0}_Hypsometry".format(reach),
                                         output_gdb_path)

# Delete files from workspace
arcpy.Delete_management("Hypsometry_all")
arcpy.Delete_management(depth_grid_name)
arcpy.Delete_management("Hypsometry")
for reach in reach_list:
    arcpy.Delete_management("{0}_Hypsometry".format(reach))

# Delete temporary files and variables
if delete_intermediate_data == True:
    arcpy.AddMessage("Deleting temporary files for {0}".format(stage))
Exemple #8
0
def preprocess(in_folder,
               clip_selector=False,
               clipping_extent=default_extent,
               bands=[4, 3, 2]):
    '''Function to preprocess imagery from larger files into PNGs for use in deep learning models'''

    # Gather all rasters in input folder, and sort by name
    arcpy.env.workspace = in_folder
    rasters = arcpy.ListRasters()
    rasters.sort()

    holding_folder = os.path.join(in_folder, 'delete')
    try:
        os.mkdir(holding_folder)
    except FileExistsError:
        print(f"{holding_folder} already exists.")
    output_folder = os.path.join(in_folder, 'output')
    print(f"Output folder at {output_folder}")
    try:
        os.mkdir(output_folder)
    except FileExistsError:
        print(f"{output_folder} already exists.")

    for raster in rasters:
        desc = arcpy.Describe(raster)
        print(f"Working on {desc.baseName}")

        # Regular expression to identify year value
        year_search = re.search(r'\d\d\d\d', desc.baseName)
        year = year_search.group()

        # If no year value present, print error and continue for loop
        if year == None:
            print('No year value found in name, skipping.')
            continue

        # If year is present, execute following steps:
        else:

            # Create scratch folder to hold working files

            try:
                temp = arcpy.management.CreateFolder(
                    holding_folder, f'delete_{desc.baseName}')
            except FileExistsError:
                print(f"{temp} already exists.")

            try:
                # Move raster into file geodatabase to enable GDB operations
                arcpy.RasterToGeodatabase_conversion(raster, temp)
                print(temp)
                print(f"Raster {desc.baseName} to Feature Layer")

                temp_folder = str(temp)
                arcpy.env.workspace = temp_folder
                raster_gdb = desc.baseName

                # Clip if necessary, and rename file to shorten length
                clipped_name = f"cr_{year}"
                if clip_selector == True:
                    arcpy.management.Clip(raster_gdb, clipping_extent,
                                          clipped_name)
                    print(f"Clipped {clipped_name}")
                else:
                    arcpy.management.Rename(raster_gdb, clipped_name)
                    print(f"Renamed {clipped_name}")

                # Create a three-band PNG composite for deep learning
                composite_name = f"cmp_{year}.png"
                arcpy.management.MakeRasterLayer(
                    clipped_name, composite_name, "", "",
                    f"{bands[0]};{bands[1]};{bands[2]}")
                arcpy.management.CopyRaster(
                    composite_name, os.path.join(output_folder,
                                                 composite_name), '', None,
                    "3.4e+38", "NONE", "NONE", '16_BIT_UNSIGNED', "NONE",
                    "NONE", "PNG", "NONE", "CURRENT_SLICE", "NO_TRANSPOSE")
                print(f"Composite PNG for {composite_name} complete.")

            except Exception as e:
                print(e)

            finally:
                arcpy.env.workspace = in_folder
                # Delete scratch folder to save space
                try:
                    arcpy.management.Delete(temp)
                except Exception as e:
                    pass
                try:
                    shutil.rmtree(temp_folder)
                except Exception as e:
                    pass
else:
    arcpy.AddMessage("Spatial Analyst checked out")

# Concatenate path
path = out_location + "\{0}{1}".format(name, ".gdb")

# Create Geodatabase
arcpy.AddMessage("Creating File Geodatabase")
arcpy.CreateFileGDB_management(out_location, name)

# Set workspace to new geodatabase
arcpy.env.workspace = path

# Import Raster
arcpy.AddMessage("Importing DEM")
arcpy.RasterToGeodatabase_conversion(input_raster, path)

# Create hillshade
if create_hillshade == True:
    arcpy.AddMessage("Creating hillshade")
    hillshade_name = "Hillshade"
    outHillShade = arcpy.sa.Hillshade(input_raster)
    outHillShade.save(hillshade_name)

# Extract spatial reference object from raster
arcpy.AddMessage("Extracting spatial reference object from raster")
spatial_reference = arcpy.Describe(input_raster).spatialReference

# Create Cross_Sections Feature Class
arcpy.AddMessage("Creating Cross_Sections feature class")
crosssections_name = "Cross_Sections"
Kullanıcının yukledigi bir dosyayi Raster Catalog'a aktaralim.
Not: Raster Catalog ArcMap'te vardır, ArcGIS Pro'da yoktur. Orada Mosaic Dataset var ama Image Server lisansı ister.

"""

import arcpy
from datetime import datetime

in_raster = arcpy.GetParameterAsText(0)
# Asagidaki sabit mosaic path'i kendinizdeki mosaic dataset path'i ile degistirin.
sabit_catalog_path = r"C:\Users\LENOVO\PycharmProjects\geoprocessingServiceOrnekler\datasources\ornekFGDB.gdb\PlanCatalog"
tarihfield = "EklenmeTarihi"

# Adim 1: Add
arcpy.RasterToGeodatabase_conversion(in_raster, sabit_catalog_path)

"""
Ben updateCursor ile devam ettim, dileyen arkadaslar asagidaki kismi kullanabilir:
# Adim 2 : Tarih Sutununu guncellemek
# Model ile ayni yapalim :)
arcpy.MakeRasterCatalogLayer_management(sabit_catalog_path, "CatalogLayer")
arcpy.SelectLayerByAttribute_management("CatalogLayer", "NEW_SELECTION", "EklenmeTarihi is NULL")
arcpy.CalculateField_management('PlanCatalog_Layer', 'EklenmeTarihi', 'datetime.datetime.now( )', 'PYTHON_9.3')

"""

# Adim 2: Tarih sutununu guncellemek
# Modeldekinden farkli bi sey yapalim :)

try:
arcpy.env.pyramid = "NONE"
arcpy.env.rasterStatistics = "NONE"
arcpy.compression = "JPEG 50"
arcpy.env.resamplingMethod = "BILINEAR"

start = time.time();
i = 0
while i < len(os.listdir(orthos)):
    file = os.listdir(orthos)[i]
    if file.endswith(".tif") | file.endswith(".jpg"):
        end = time.time()
        print (str(i) + " / " + str(len(os.listdir(orthos))))
        print("Remaining time: " + str(datetime.timedelta(seconds=int(end - start) / i) * (len(os.listdir(orthos)) - i)))
        # Expecting to have a .tfw file first.
        if i == 0 | i == 1:
            arcpy.RasterToGeodatabase_conversion(orthos + "/" + file, gdb);
            if file.endswith(".tif"):
                arcpy.CopyRaster_management(gdb + "/T" + file[:file.index(".")], gdb + "/" + name)
                arcpy.Delete_management(gdb + "/T" + file[:file.index(".")])
            else:
                arcpy.CopyRaster_management(gdb + "/" + file[:file.index(".")], gdb + "/" + name)
                arcpy.Delete_management(gdb + "/" + file[:file.index(".")])
            start = time.time()
        else:
            arcpy.Mosaic_management(inputs = orthos + "/" + file,
                                    target = gdb + "/" + name,
                                    mosaic_type = "LAST", colormap = "FIRST", background_value = "", nodata_value = "",
                                    onebit_to_eightbit = "NONE", mosaicking_tolerance = "0", MatchingMethod = "NONE")
    i += 1

print("BUILDING PYRAMIDS")
Exemple #12
0
sys.setdefaultencoding('UTF-8')
import arcpy
from arcpy import env
wspath = "D:\\bysj\\fea"
env.workspace = wspath
#将shapefile导入文件数据库中
env.workspace = wspath
for fc in arcpy.ListFiles('*.shp'):
    env.workspace = "D:\\bysj\\file\\chen.gdb"
    fcfgb = arcpy.ListFeatureClasses()
    fc = fc.split('.')[0]
    if fc in fcfgb:
        print(fc + " 已经存在!")
    else:
        env.workspace = wspath
        arcpy.FeatureClassToGeodatabase_conversion(fc,
                                                   "D:\\bysj\\file\\chen.gdb")

#栅格数据
env.workspace = wspath
for fc in arcpy.ListRasters():
    s = fc
    env.workspace = "D:\\bysj\\file\\chen.gdb"
    fcfgb = arcpy.ListRasters()
    fc = fc.split('.')[0]
    if fc in fcfgb:
        print(fc + " 已经存在!")
    else:
        env.workspace = wspath
        arcpy.RasterToGeodatabase_conversion(wspath + os.sep + s, fgb)
Exemple #13
0
# Check out 3D Analyst and Spatial Analyst licenses
arcpy.CheckOutExtension("3D")
arcpy.CheckOutExtension("Spatial")

# This creates list of all tiles within MN from text file.
DEMlist = open("I:\RasterMosaic\DEM_MN_FeatureList.txt").readlines()

# This loop copies the files in GeoTiffDEM that are in DEMlist (within state boundary) to a new folder as 32 bit float, then into a geodatabase.
for fn in DEMlist:

    infile = fn[:-1] + ".tif"

    outfile = fn[:-1] + ".tif"

    outraster = out_workspace + "\\" + outfile

    # This copies all tiles in list as 32 bit float to a new folder
    outcopy = arcpy.CopyRaster_management(
        infile,
        outraster,
        pixel_type="32_bit_float",
    )

    # This copies all files created in Copy Raster to geodatabase, DEM_MN.gdb
    arcpy.RasterToGeodatabase_conversion(outcopy, "I:\GDBs\DEM_MN.gdb")

# Check in 3D Analyst and Spatial Analyst licenses
arcpy.CheckInExtension("3D")
arcpy.CheckInExtension("Spatial")
def rasterToGeodatabase(Input_Rasters, output_geodatabase):
   arcpy.RasterToGeodatabase_conversion(Input_Rasters, output_geodatabase)
Exemple #15
0
import arcpy
from arcpy import env

env.workspace = "D:/PATH/TO/WORKSPACE/DIRECTORY"

# Create a geodatabase to store rasters
out_folder_path = "D://YOUR/OUTPUT/DIR"
outgdb_name = "outgdb.gdb"
arcpy.CreateFileGDB_management(out_folder_path, outgdb_name)

# Lists all the rasters in your workspace directory
rasters_list = arcpy.ListRasters()

# Imports all the rasters to the geodatabase created above
arcpy.RasterToGeodatabase_conversion(";".join(rasters_list),
                                     out_folder_path + "/" + outgdb_name)