def image_psh(ms, pan, psh, bands, bands_ref, enhanced):
    fili = ms
    dbic = bands
    dbic_ref = bands_ref
    fili_pan = pan
    dbic_pan = [1]
    filo = psh.replace('.tif', '.pix')
    dboc = dbic
    enhance = enhanced  # apply the color enhancement operation
    nodatval = [
        0.0
    ]  # zero-valued pixels in any input image are excluded from processing
    poption = "OFF"  # resampling used to build pyramid overview images
    pansharp(fili, dbic, dbic_ref, fili_pan, dbic_pan, filo, dboc, enhance,
             nodatval, poption)
    fili = filo
    filo = psh
    dbiw = []
    dbic = dbic
    dbib = []
    dbvs = []
    dblut = []
    dbpct = []
    ftype = "TIF"
    foptions = "TILED256"
    fexport(fili, filo, dbiw, dbic, dbib, dbvs, dblut, dbpct, ftype, foptions)
    if os.path.exists(filo):
        for file in (fili, filo + '.pox'):
            if os.path.exists(file):
                os.remove(file)
예제 #2
0
def main(args):
    if not os.path.isfile(args[1]):
        print "Input argument must be a PIX file"
        exit(1)

    channels = []
    try:
        channels = [int(n) for n in args[2].split(",")]
    except ValueError as e:
        print "Conversion error [STRING >> INT]", e
        exit(2)

    out = args[1].replace(".pix", ".tif")

    fexport(args[1], out, [], channels, [], [], [], [], u"TIF",
            u"TILED512 LZW")
예제 #3
0
def make_pca(merged_input, pca_out, identifier):
    start_time = time.time()
    print "Starting Principal Component Analysis for file %s" % identifier
    pca_rep = os.path.join(pcadir, "PCA_" + identifier + "_report.txt")
    fexport(fili=merged_input,
            filo=pca_out,
            dbic=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            ftype="PIX")
    try:
        Report.clear()                                          # Clear report file
        enableDefaultReport(pca_rep)                            # Change output folder location

        pcimod(file=pca_out,
               pciop="ADD",
               pcival=[0, 0, 3])                                # Add 3 16 bit unsigned channels
        pca(file=pca_out,
            dbic=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],               # Use first ten bands
            eign=[1, 2, 3],                                     # Output first three eigenchannels
            dboc=[11, 12, 13],                                  # Output to 3 new channels
            rtype="LONG")                                       # Output extended report format
    except PCIException, e:
        print e
예제 #4
0
    def export_file(self, in_file, out_file, ftype, foption):
        """
        Exports image data

        Detailed description
            Transfers the specified image and auxiliary information from a source file
            to an output file of a different data type

        Parameters:
            in_file     -- Input file
            out_file    -- Output file
            ftype       -- Specifies the file format for the new output file
            foption     -- Specifies the file creation options


        Return value:
            Error statement if error occurs.
            
        Limits and constraints:
        
        """
        try:
            logging.info('       Executing: OrthoMosaic.export_file')            
            fili     = in_file
            filo     = out_file
            dbiw     = []
            dbic     = [1,2]
            dbib     = []
            dbvs     = []
            dblut    = []
            dbpct    = []
            ftype    = ftype
            foptions = foption
            fexport(fili, filo, dbiw, dbic, dbib, dbvs, dblut, dbpct, ftype, foptions)
            logging.info('          Successfully completed OrthoMosaic.export_file: fexport')

        except PCIException, e:
            EGS_utility.EGSUtility().error('export_file(): {:s}'.format(e))
예제 #5
0
    def export_vegflood(self, in_file, out_file, veg_chan):
        """
        Export flooded vegetation as a geotiff

        Parameters:
            in_file  -- Input file
            out_file -- Out file
            veg_chan -- Bit segment of vegetation land cover

        Return value:
            Error statement if error occurs.

        Limits and constraints:

        """
        try:
            os.remove(out_file)
        except OSError:
            pass

        util = EGS_utility.EGSUtility()
        new_chans = util.add_8_channel(in_file)

        try:
            logging.info('       Executing: VegFloodProcess.export_vegflood')
            file = in_file
            dboc = [int(new_chans[0])]
            valu = [0]
            dbow = []
            clr(file, dboc, valu, dbow)
            logging.info(
                '          Successfully completed VegFloodProcess.export_vegflood: clr'
            )

            file = in_file
            dbib = [veg_chan]  # Select bitmaps for encoding
            dboc = [int(new_chans[0])]  # Select channel to be encoded
            valu = [1]  # Specify gray level values
            map(in_file, dbib, valu, dboc)
            logging.info(
                '          Successfully completed VegFloodProcess.export_vegflood: map'
            )

            fili = in_file
            filo = out_file
            dbiw = []
            dbic = [int(new_chans[0])]
            dbib = []
            dbvs = []
            dblut = []
            dbpct = []
            ftype = "tif"
            foptions = ""
            fexport(fili, filo, dbiw, dbic, dbib, dbvs, dblut, dbpct, ftype,
                    foptions)
            logging.info(
                '          Successfully completed VegFloodProcess.export_vegflood: fexport'
            )

        except PCIException, e:
            EGS_utility.EGSUtility().error('export_vegflood(): {:s}'.format(e))
print("\t\tSTEP 4. : MOSAICKING : Please be patient")
automos(
    mfile=atcor_out,
    dbiclist="4,3,2"  # bands to process
    ,
    mostype='full',
    filo=mosaic_out + "/" + "mosaic.pix"
    #startimg = mos_start,                            # by default number one / refer to line 101 to modify
    ,
    radiocor='adaptive',
    balmthd='overlay',
    cutmthd='mindiff',
    filvout=shp_out + "/" + "cutlines.shp")  # output for cutlines

# -----------------------------------------------------
# Step 5 Export Pix to Tif/PNG
# -----------------------------------------------------
fexport(
    fili=mosaic_out + "/" + "mosaic.pix"  # Input pix
    ,
    filo=mosaic_out + "/" + "mosaic.tif",
    dbic=[1, 2, 3]  # Channels
    ,
    ftype="TIF")

winsound.MessageBeep()
ctypes.windll.user32.MessageBoxW(
    0,
    "Sucess! All Landsat 8 Imagering sucessfully mosaicked. Don't forget to save your files before executing again",
    "Message", 1)
예제 #7
0
print "              Geomatica - Export SIEVE Filter to 32bit GeoTIFF"
print "***************************************************************"
print ""

filo	=	outputs + '\\sieve_filter.tif'
dbiw	=	[]
dbic3	=	[8] #Output raster channel
dbib	=	[]
dbvs	=	[]
dblut	=	[]
dbpct	=	[]
ftype	=	"TIF"
foptions =  u""

try:
	fexport( file, filo, dbiw, dbic3, dbib, dbvs, dblut, dbpct, ftype, foptions )
except PCIException, e:
    print e
except Exception, e:
    print e

print "Export Complete!"
print ""

print ""
print "***************************************************************"
print "              ArcGIS - Convert Raster To Polygon"
print "***************************************************************"
print ""

print "Creating File Geodatabase"
예제 #8
0
    def merge_filter_export(self, in_file, in_file2, out_file, out_file2, out_file3, hole_size):
        """
        Imports, merges, filters and exports flooded products.

        Import flood products into PCIPIX format, merge products, filters to remove holes / areas.
        Outputs resulting products as compressed geotif and shapefile.

        Merges image value polygons smaller than a user-specified
        threshold with the largest neighboring polygon

        Parameters:
            in_file    -- Input file1
            in_file2   -- Input file2
            out_file   -- Working PCIPIX file
            out_file2  -- Resuling output geotif
            hole_size  -- threshold for filter (hectares)

        Return value:
            Error statement if error occurs.

        """

        #import required PCI Geomatica modules
        import pci
        from pci.sieve import *
        from pci.fimport import *
        from pci.fexport import *
        from pci.thmrovr import *
        from pci.mosaic import *
        from pci.thmrmer import *
        from pci.model import *
        from pci.nspio import Report, enableDefaultReport
        from pci.exceptions import PCIException
        from pci.ras2poly import *
        import arcpy
        from osgeo import gdal, ogr, osr
        from gdalconst import GA_Update

        try:
            util        =       EGS_utility.EGSUtility()

            #Import first image (flooded vegetation) into PCIPIX file
            logging.info('       Executing: MergeProcess.merge_filter_export')
            fili        =       in_file
            filo        =       out_file
            dbiw        =       []
            poption     =       ""
            dblayout    =       ""           #Defaults to "BAND"
            Report.clear()
            fimport(fili, filo, dbiw, poption, dblayout)
            enableDefaultReport('term')
            logging.info('          Successfully completed MergeProcess.merge_filter_export: fimport')

            #Import second image (open water) into PCIPIX file
            new_chans   =       EGS_utility.EGSUtility().add_8_channel(out_file)
            fili        =       in_file2
            dbic        =       [1]     # use channel 1
            dbvs        =       []      # default, no cutline defined
            dblut       =       []      # default, no lookup table
            filo        =       out_file
            dboc        =       [int(new_chans[0])]     # overwrite channel 1
            blend       =       []      # default, no blending
            backval     =       []      # default, 0
            mosaic( fili, dbic, dbvs, dblut, filo, dboc, blend, backval )
            logging.info('          Successfully completed MergeProcess.merge_filter_export: mosaic')

            # Convert values using MODEL so 255 = 0
            file        =       out_file
            source_model = """if (%2 = 255) then
                                        %2 = 0
                                        endif"""
            model( file, source=source_model)

            #Merge two image together, possible use thmrovr for one step instead of two
            merge_chan  =       util.add_8_channel(out_file)
            fili        =       out_file    # input file
            filo        =       out_file    # output file will be created
            dbic        =       [1,int(new_chans[0])]   # input thematic raster channels
            dbib        =       []      # no bitmap mask
            dboc        =       [int(merge_chan[0])]
            omethod     =       "UNION"      # default, "UNION"
            thmrovr( fili, filo, dbic, dbib, dboc, omethod )
            logging.info('          Successfully completed MergeProcess.merge_filter_export: thmrovr')

            # Combine values using MODEL so zero = not flooded, 255 = flooded
            file        =       out_file
            source_model = """if (%3 >= 1) then
                                        %3 = 255
                                        endif"""
            model( file, source=source_model)

            #Determine filter size as pixel number
            filtered_chan   =       util.add_8_channel(out_file)
            pixelwidth      =       util.gdal_geotransform(out_file)[1]
            pixelheight      =      util.gdal_geotransform(out_file)[5]
            logging.info('          pixelwidth: ' + str(pixelwidth))
            logging.info('          pixelheight: ' + str(pixelheight))
            num_pixel       =       int((hole_size * 10000)/abs(pixelwidth *  pixelheight)) # hole_size is in hectares
            logging.info('          Number of pixels for threshold hole size: ' + str(num_pixel))

            #Filter in order to remove holes
            file        =       out_file
            dbic        =       [int(merge_chan[0])]
            dboc        =       [int(filtered_chan[0])]
            sthresh     =       [num_pixel]     # polygon size threshold in
            keepvalu    =       []      # no keep value
            connect     =       []      # default, 4-connection
            sieve( file, dbic, dboc, sthresh, keepvalu, connect )
            logging.info('          Successfully completed MergeProcess.merge_filter_export: sieve')
            #EGS_utility.EGSUtility().raster_his(out_file,int(filtered_chan[0]))

            #Export resulting product as a geotif
            fili        =       out_file
            filo        =       out_file2
            dbiw        =       []
            dbic        =       [int(filtered_chan[0])]
            dbib        =       []
            dbvs        =       []
            dblut       =       []
            dbpct       =       []
            ftype       =       "tif"
            foptions    =       "LZW"
            fexport( fili, filo, dbiw, dbic, dbib, dbvs, dblut, dbpct, ftype, foptions )
            logging.info('          Successfully completed MergeProcess.merge_filter_export: fexport')

            fili     = out_file         # input raster file
            dbic     = [int(filtered_chan[0])] # using channel 6 from irvine.pix
            filo     = out_file         # output file to be created
            smoothv  = ""               # default, YES vectors are smoothed
            dbsd     = ""               # defaults to "Created from Raster"
            ftype    = ""               # default, PIX
            foptions = ""               # output format options
            ras2poly(fili, dbic, filo, smoothv, dbsd, ftype, foptions)
            logging.info('          Successfully completed MergeProcess.merge_filter_export: ras2poly')

            # Export resulting product as a shapefile
            # PCI creates shapefile with projection 'UTM 18 S E008 ', compared to 'UTM 18 T D122'
            # These projections are the same projection, as E008 is the ellipsoid used by NAD 1983.
            # but opted for arcpy export
            fili        =       out_file
            filo        =       out_file3
            dbiw        =       []
            dbic        =       []
            dbib        =       []
            dbvs        =       [3]
            dblut       =       []
            dbpct       =       []
            ftype       =       "shp"
            foptions    =       ""
            #fexport( fili, filo, dbiw, dbic, dbib, dbvs, dblut, dbpct, ftype, foptions )
            arcpy.RasterToPolygon_conversion(out_file2, out_file3, "NO_SIMPLIFY", "")
            logging.info('          Successfully completed MergeProcess.merge_filter_export: arcpy.RasterToPolygon_conversion')


        except PCIException, e:
            EGS_utility.EGSUtility().error('merge_filter_export(): {:s}'.format(e))
print ""

#Export DSM to 32bit GeoTIFF (PCI Geomatica)
fili = filedsm
filo = intermediate_outputs + 'dsm_urban.tif'
dbiw = []
dbic = [1]
dbib = []
dbvs = []
dblut = []
dbpct = []
ftype = "TIF"
foptions = u""

try:
    fexport(fili, filo, dbiw, dbic, dbib, dbvs, dblut, dbpct, ftype, foptions)
except PCIException, e:
    print e
except Exception, e:
    print e

print ""
print "***************************************************************"
print "                 esri - Running Visibility Analysis                 "
print "***************************************************************"
print ""

print "Creating File Geodatabase"
arcpy.CreateFileGDB_management(
    intermediate_outputs,
    'pci_esri-solution.gdb')  #Create output file GeoDatabase
        dboc=[7,8,9,10,11,12],                          #where to place them (on newly created channel)
        rtype="long")
except PCIException as e:
         print (e)
except Exception as e:
         print (e)
finally:
    enableDefaultReport('Term')


#set location of infile and outfile for fexport
pix_12band = clip_scene + "/" + "scene_clipped.pix"
pix_3band = final_dir + "/" + "halifax_pca.pix" 
channel2export = [7,8,9,10,11,12]                    #choose channels here
try:
    fexport(fili = pix_12band, filo =pix_3band, dbic = channel2export)  
except PCIException as e:
    print (e)
except Exception as e:
    print (e)

tiff_3band = final_dir + "/" + "halifac_pca.tif"

try:
    fexport(fili=pix_12band, filo = tiff_3band, dbic = channel2export, ftype = "TIF" )
except PCIException as e:
    print (e)
except Exception as e:
    print (e)

#open the directory to view final image    
예제 #11
0
def land_cover(pixin, vout, rout, identifier, clouds):
    start_time = time.time()                                        # Start timer
    print "Generating land cover classification..."
    pct_string = "PCT generated using RGB channels from file %s" % identifier
    id_string = "Classification from file %s." % identifier
    landscr = os.path.join(landcoverdir, identifier + "_landcover.pix")     # Scratch pix file
    rgb8bit = os.path.join(landcoverdir, identifier + "_rgb8bit.pix")       # Rescaled 8-bit pix file
    fexport(fili=pixin,                                             # Input with PCA
            filo=landscr,                                           # Output scratch file
            dbiw=[],
            dbic=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],       # Use all channels
            dbib=[2],
            dbvs=[],
            dblut=[],
            dbpct=[],
            ftype="PIX",                                            # PIX filetype
            foptions="")
    pcimod(file=landscr,                                            # Output scratch PIX file
           pciop='ADD',                                             # Modification mode "Add"
           pcival=[0, 2, 0, 0])                                     # Task - add two 16U channels
    if clouds:
        kclus(file=landscr,                                         # Run classification on scratch file
              dbic=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],     # Use all image layers
              dboc=[14],                                            # Output to blank layer
              mask=[2],                                             # Use not-cloud mask
              numclus=[24],                                         # 24 clusters (not all will be used, but
              seedfile='',                                          # this avoids cluster confusion)
              maxiter=[20],
              movethrs=[0.01],
              siggen="YES",                                         # Save signature layers
              backval=[],
              nsam=[])
    else:
        kclus(file=landscr,                                         # Run classification on scratch file
              dbic=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],     # Use all image layers
              dboc=[14],                                            # Output to blank layer
              numclus=[24],                                         # 24 clusters (not all will be used, but
              seedfile='',                                          # this avoids cluster confusion)
              maxiter=[20],
              movethrs=[0.01],
              siggen="YES",  # Save signature layers
              backval=[],
              nsam=[])
    print "Land cover classification for file %s completed." % identifier
    print "Creating a colour table for classification result..."
    scale(fili=landscr,                                             # Rescale layers to 8-bit for use with pctmake
          filo=rgb8bit,
          dbic=[1, 2, 3, 14],                                       # Rescale RGB and classification layer
          dboc=[],
          sfunct="LIN",
          datatype="8U",                                            # Scale to 8-bit unsigned
          ftype="PIX")                                              # PIX format
    stretch(file=rgb8bit,                                           # Creat lookup tables for histogram enhancement
            dbic=[1],                                               # Stretch band 1
            dblut=[],
            dbsn="LinLUT",
            dbsd="Linear Stretch",
            expo=[0.5])                                               # Linear stretch
    stretch(file=rgb8bit,
            dbic=[2],                                               # Stretch band 2
            dblut=[],
            dbsn="LinLUT",
            dbsd="Linear Stretch",
            expo=[0.5])                                               # Linear stretch
    stretch(file=rgb8bit,
            dbic=[3],                                               # Stretch band 3
            dblut=[],
            dbsn="LinLUT",
            dbsd="Linear Stretch",
            expo=[0.5])                                               # Linear stretch
    pctmake(file=rgb8bit,                                           # Make Colour table from rescaled RGB
            dbic=[3, 2, 1],                                         # RGB layers
            dblut=[4, 3, 2],                                        # Apply LUT stretch enhancement
            dbtc=[4],                                               # Classification layer
            dbpct=[],                                               # Make new PCT
            mask=[],
            dbsn="TC_PCT",                                          # PCT name
            dbsd=pct_string)                                        # PCT description
    print "Colour table generated from RGB layers and applied to %s classification result." % identifier
    print "Converting Raster PCT to ArcMap Colour Layer..."
    pct_txt = os.path.join(landcoverdir, identifier + "_pct.txt")
    pctwrit(file=rgb8bit,                                           # Export constructed PCT to text file
            dbpct=[5],                                              # PCT channel
            pctform="ATT",                                          # Write in attribute format
            tfile=pct_txt)
    clrfile = os.path.join(landcoverdir,identifier + "_landcover.clr")
    if os.path.isfile(clrfile):                                     # Using append mode, so make sure file is deleted
        os.remove(clrfile)
    pct = open(pct_txt, "r")                                        # Open exported PCT text file in read mode
    clr = open(clrfile, "w")                                        # Open new CLR file in write mode
    for line in pct:
        if line[0] != "!" and line[3] == " ":                       # If line[3] not blank, line is unused range
            a1 = line[8]                                            # and if line starts with "!" it is the file header
            a2 = line[9]                                            # Number range is 0-255 so three possible digits
            a3 = line[10]                                           # Assign as int() to ignore blank digit spaces
            att = int(a1 + a2 + a3)                                 # Read number representing attribute
            r1 = line[15]
            r2 = line[16]
            r3 = line[17]
            red = int(r1 + r2 + r3)                                 # Read number representing red value
            g1 = line[20]
            g2 = line[21]
            g3 = line[22]
            green = int(g1 + g2 + g3)                               # Read number representing green value
            b1 = line[25]
            b2 = line[26]
            b3 = line[27]
            blue = int(b1 + b2 + b3)                                # Read number representing blue value
            clr.write("%s %s %s %s\n" % (att, red, green, blue))    # Write attribute and RGB value to CLR file
    clr.close()
    print "Raster PCT converted to ArcMap colour layer."
    print "Exporting classified raster to tif..."
    fexport(fili=rgb8bit,                                           # Export raster
            filo=rout,                                              # Raster output location
            dbic=[4],                                               # Classification channel
            dbpct=[5],                                              # Colour table channel (2,3,4 are LUT)
            ftype="TIF",                                            # TIF format
            foptions="")
    print "Classification exported to %s." % rout
# ------------------------------------------------------------------------------------------------------------------- #
#    TODO this section is included for reference, although not functional currently. Future exploration of automatic
#    TODO application of symbology would be desirable.
#    print "Applying colour map to layer file..."
#    workspace = os.path.join(workingdir, "sable.gdb")  # Define GDB workspace
#    ras_lyr = identifier + "_raster_lyr"  # Define feature layer name for polygon output
#    lyr_out = rout[:-4] + ".lyr"
#    arcpy.env.workspace = workspace  # Set default workspace
#    arcpy.env.overwriteOutput = True
#    arcpy.env.outputCoordinateSystem = "PROJCS['WGS_1984_UTM_Zone_20N',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',0.0],PARAMETER\
#        ['Central_Meridian',-63.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]"
#    arcpy.BuildRasterAttributeTable_management(in_raster=rout)
#    arcpy.MakeRasterLayer_management(in_raster=rout,
#                                     out_rasterlayer=ras_lyr)
#    arcpy.SaveToLayerFile_management(in_layer=ras_lyr,
#                                     out_layer=lyr_out,
#                                     is_relative_path="RELATIVE")
#    arcpy.mapping.UpdateLayer(d)
#    print "Exported layer file to %s" % lyr_out
#    print "Applying colour map to layer file..."
#   arcpy.AddColormap_management(in_raster=lyr_out,
#                                 input_CLR_file=clrfile)
#    print "Colour map applied to ArcMap layer file %s." % lyr_out
# ------------------------------------------------------------------------------------------------------------------- #
    print "Exporting classification to shapefile..."
    ras2poly(fili=rgb8bit,                                          # Export to vector
             dbic=[4],                                              # Use classification channel
             filo=vout,                                             # Vector output location
             smoothv="NO",                                          # Don't smooth boundaries
             dbsd=id_string,                                        # Layer description string
             ftype="SHP",                                           # Shapefile format
             foptions="")
    print "Vector export complete. Wrote to %s." % vout
    os.remove(landscr)                                              # Delete intermediate PIX files
    os.remove(rgb8bit)
    completion_time = time.time() - start_time                      # Calculate time to complete
    print "Land cover classification process completed for image %s in %i seconds." % (identifier, completion_time)
예제 #12
0
def coastline(pixin, polygonout, lineout, lineout_smooth, identifier, clouds):
    start_time = time.time()
    print "Generating coastline classification..."
    id_string = "Coastline from file %s." % identifier
    coastscr = os.path.join(coastdir, identifier + "_coastline.pix")
    fexport(fili=pixin,                                             # Input with PCA
            filo=coastscr,                                          # Output scratch file
            dbiw=[],
            dbic=[11, 12, 13],                                      # PCA channels
            dbib=[2],
            dbvs=[],
            dblut=[],
            dbpct=[],
            ftype="PIX",                                            # PIX filetype
            foptions="")
    pcimod(file=coastscr,                                           # Output scratch PIX file
           pciop='ADD',                                             # Modification mode "Add"
           pcival=[0, 2, 0, 0])                                     # Task - add two 16U channels
    if clouds:
        kclus(file=coastscr,                                        # Run classification on scratch file
              dbic=[1, 2, 3],                                       # Use three PCA layers
              dboc=[4],
              mask=[2],                                             # Use the not-cloud mask
              numclus=[2],                                          # Two clusters - land, ocean
              seedfile='',
              maxiter=[20],
              movethrs=[],
              siggen="YES",
              backval=[],
              nsam=[])
    else:
        kclus(file=coastscr,                                        # Run classification on scratch file
              dbic=[1, 2, 3],                                       # Use three PCA layers
              dboc=[4],                                             # Output to blank layer
              numclus=[2],                                          # Two clusters - land, ocean
              seedfile='',
              maxiter=[20],
              movethrs=[],
              siggen="YES",
              backval=[],
              nsam=[])
    ras2poly(fili=coastscr,                                         # Use scratch PIX file
             dbic=[4],                                              # Use classification channel
             filo=polygonout,                                       # Polygon SHP output location
             smoothv="YES",                                         # Smooth boundaries
             dbsd=id_string,                                        # Layer description string
             ftype="SHP",                                           # Shapefile format
             foptions="")
    selpoints = os.path.join(workingdir,"selection_points","selection_polygons.shp")
    workspace = os.path.join(workingdir,"sable.gdb")                # Define GDB workspace
    polygonout_lyr = identifier + "_polygon_lyr"                    # Define feature layer name for polygon output
    arcpy.env.workspace = workspace                                 # Set default workspace
    arcpy.env.overwriteOutput = True
    arcpy.env.outputCoordinateSystem = "PROJCS['WGS_1984_UTM_Zone_20N',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',0.0],PARAMETER\
    ['Central_Meridian',-63.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]"
    arcpy.MakeFeatureLayer_management(polygonout, polygonout_lyr)   # Make polygon feature layer
    arcpy.AddField_management(in_table=polygonout,                  # Add new dissolve field
                              field_name="DISV",
                              field_type="SHORT",
                              field_precision=1,
                              field_scale=0,
                              field_is_nullable="NULLABLE",
                              field_is_required="NON_REQUIRED")
    cb = "def calDisv(area):\\n    if area > 1000000000:\\n        return 0\\n    elif area < 1000000000:\\n        return 1"
    arcpy.CalculateField_management(in_table=polygonout,            # Calculate dissolve field
                                    field="DISV",
                                    expression="calDisv(!Area!)",   # =0 if Ocean, =1 otherwise
                                    expression_type="PYTHON",
                                    code_block=cb)
    polygons_dissolved = identifier + "_poly_dissolved"
    arcpy.Dissolve_management(in_features=polygonout,               # Dissolve island polygons
                              out_feature_class=polygons_dissolved,
                              dissolve_field="DISV",
                              multi_part="SINGLE_PART",
                              unsplit_lines="DISSOLVE_LINES")
    polygondisv_lyr = identifier + "_polygon_disv_lyr"
    arcpy.MakeFeatureLayer_management(polygons_dissolved, polygondisv_lyr)  # Make polygon feature layer
    arcpy.SelectLayerByAttribute_management(in_layer_or_view=polygondisv_lyr,
                                            selection_type="NEW_SELECTION",
                                            where_clause="DISV=1")
    island_poly_dissolved = identifier + "island_poly_dissolved"
    arcpy.CopyFeatures_management(in_features=polygondisv_lyr,
                                  out_feature_class=island_poly_dissolved)
    island_poly_disv_lyr = identifier + "_isl_poly_disv_lyr"
    arcpy.MakeFeatureLayer_management(island_poly_dissolved, island_poly_disv_lyr)  # Make polygon feature layer
    # Select island polygons that contain selection circle polygons (small, basically points).
    # These points are placed where the island is likely to exist.
    # Remove selection of features larger than 1B sq. m - this feature most likely represents ocean.
    try:                                                    # Does feature layer 'selpoints_lyr' exist yet?
        arcpy.SelectLayerByLocation_management(island_poly_disv_lyr,'CONTAINS','selpoints_lyr','','NEW_SELECTION')
    except:                                                 # Didn't work, so create 'selpoints_lyr' first
        arcpy.MakeFeatureLayer_management(selpoints, 'selpoints_lyr')
        arcpy.SelectLayerByLocation_management(island_poly_disv_lyr, 'CONTAINS', 'selpoints_lyr', '', 'NEW_SELECTION')

    # Convert polygon features to polyline
    arcpy.PolygonToLine_management(island_poly_disv_lyr,lineout,'IDENTIFY_NEIGHBORS')

    # Smooth line features to fix zig-zag from raster cells
    arcpy.cartography.SmoothLine(lineout,lineout_smooth,"PAEK",50,"")
    os.remove(coastscr)
    completion_time = time.time() - start_time                      # Calculate time to complete
    print "Coastline vector completed in %i seconds. Written to file %s." % (completion_time, lineout_smooth)
    return lineout_smooth
예제 #13
0
def main():
    if os.path.isdir(indir) == False:
        print "\tMissing input folder!"
        print "\tAdd unzipped input files to input folder"
    if os.path.isdir(corrdir) == True:
        print "\tClearing corrected folder"
        shutil.rmtree(corrdir)  # Delete \corrected
        os.mkdir(corrdir)  # Create \corrected
    else:
        os.mkdir(corrdir)  # Create \corrected
    if os.path.isdir(pixdir) == True:
        print "\tClearing pix folder"
        shutil.rmtree(pixdir)  # Delete \pix
        os.mkdir(pixdir)  # Create \pix
    else:
        os.mkdir(pixdir)  # Create \pix

    if os.path.isdir(mosdir) == True:
        print "\tClearing mosaic folder"
        shutil.rmtree(mosdir)  # Delete \mosaic
        os.mkdir(mosdir)  # Create \mosaic
    else:
        os.mkdir(mosdir)  # Create \mosaic
    print "-" * 22 + "Step 1" + "-" * 22
    readtopix(indir)  # Convert raw input to pix
    print "-" * 22 + "Step 2" + "-" * 22
    for i in range(len(pixfiles)):
        hazeoutput = pixfiles[i][:9] + "_hzrm.pix"
        atcoroutput = pixfiles[i][:9] + "_atcor.pix"
        correction(pixfiles[i], hazeoutput, atcoroutput)  # Correction
        shutil.move(atcoroutput, corrdir)  # Move corrected output
        print "\tCorrected %s." % pixfiles[i]
        print "\tCorrected file moved to %s." % corrdir
    print "-" * 22 + "Step 3" + "-" * 22
    print "\tStarting Mosaicking process ..."
    automos(
        mfile="/corrected"  # Mosaic files in \corrected
        ,
        mostype="FULL"  # Full format mosaic
        ,
        filo="mosaic/mosaic_out.pix"  # Output file
        ,
        ftype="PIX"  # Output to pix
        ,
        radiocor="NONE"  # No radiometric corr.
        ,
        balmthd="NONE"  # No balancing
        ,
        cutmthd="MINDIFF"  # Minimum difference cut method
        ,
        filvout="mosaic/cutlines.shp")  # Output cutlines
    print "\tMosaicking process completed."
    print "-" * 22 + "Step 4" + "-" * 22
    enhance("mosaic/mosaic_out.pix", "mosaic/mosaic_enhanced.pix")
    print "-" * 22 + "Step 5" + "-" * 22
    print "\tExporting Mosaic to TIF format..."
    fexport(
        fili="mosaic/mosaic_enhanced.pix"  # Input pix
        ,
        filo="mosaic/mosaic_enhanced.tif"  # Output tif
        ,
        dbic=[1, 2, 3]  # Channels
        ,
        ftype="TIF")
    print "\tFormat conversion complete."
    print "\tThe Mosaicking script has finished running."
    print "=" * 50