예제 #1
0
def saveRaster(image, path, attributes, minArea):
    image = image.astype(int)
    r, c = np.shape(image)
    rasterRAT = gdal.RasterAttributeTable()
    rasterRAT.SetRowCount(len(attributes))
    rasterRAT.CreateColumn('value', gdal.GFT_Integer, gdal.GFU_Generic)
    rasterRAT.CreateColumn('class_name', gdal.GFT_String, gdal.GFU_Name)
    for i in range(len(attributes)):
        rasterRAT.SetValueAsInt(i, 0, i)
        rasterRAT.SetValueAsString(i, 1, attributes[i])
    output_raster = gdal.GetDriverByName('GTiff').Create(
        path, c, r, 1, gdal.GDT_Int32)
    output_raster.GetRasterBand(1).WriteArray(image)
    if (minArea < 5 and minArea > 0):
        gdal.SieveFilter(output_raster.GetRasterBand(1), None,
                         output_raster.GetRasterBand(1), minArea, 4, [], None,
                         None)
    if minArea >= 5:
        gdal.SieveFilter(output_raster.GetRasterBand(1), None,
                         output_raster.GetRasterBand(1), 5, 4, [], None, None)
    if minArea >= 15:
        gdal.SieveFilter(output_raster.GetRasterBand(1), None,
                         output_raster.GetRasterBand(1), 15, 4, [], None, None)
        gdal.SieveFilter(output_raster.GetRasterBand(1), None,
                         output_raster.GetRasterBand(1), minArea, 4, [], None,
                         None)
    output_raster.GetRasterBand(1).SetDefaultRAT(rasterRAT)
예제 #2
0
def sieveRasterMemory(raster,
                      threshold,
                      output='',
                      dstnodata=0,
                      pixelConnection=8):

    # input band
    if isinstance(raster, str):
        data = gdal.Open(raster)
    elif isinstance(raster, gdal.Dataset):
        data = raster
    else:
        raise Exception("Input raster file not managed")

    srcband = data.GetRasterBand(1)

    # output band
    dst_ds, dstband = prepareBandRasterDataset(raster)

    gdal.SieveFilter(srcband, srcband, dstband, threshold, pixelConnection)

    outformat = 'MEM'
    if os.path.splitext(output)[1] == ".tif":
        outformat = "GTiff"

    sievedRaster = gdal.Warp(output, dst_ds, dstNodata=dstnodata, multithread=True, format=outformat, \
                             warpOptions=[["NUM_THREADS=ALL_CPUS"],["OVERWRITE=TRUE"]])
    return sievedRaster
예제 #3
0
def sieve_filter(input_file, output_file, pp_threshold):

    shutil.copy(input_file, output_file)
    ds = gdal.Open(input_file)
    output = gdal.Open(output_file, gdal.GA_Update)

    gdal.SieveFilter(ds.GetRasterBand(1), None, output.GetRasterBand(1),
                     pp_threshold, 8)

    output.FlushCache()
    ds.FlushCache()
    ds = None
    ouput = None
예제 #4
0
def sieve(image, dst_filename, convdate):
    # 1. Remove all single pixels

    #First create a band in memory that's that's just 1s and 0s
    src_ds = gdal.Open(image, gdal.GA_ReadOnly)
    srcband = src_ds.GetRasterBand(1)
    srcarray = srcband.ReadAsArray()
    srcarray[srcarray > 0] = 1

    mem_rast = save_raster_memory(srcarray, image)
    mem_band = mem_rast.GetRasterBand(1)

    #Now the code behind gdal_sieve.py
    maskband = None
    drv = gdal.GetDriverByName('GTiff')
    dst_ds = drv.Create(dst_filename, src_ds.RasterXSize, src_ds.RasterYSize,
                        1, srcband.DataType)
    wkt = src_ds.GetProjection()
    if wkt != '':
        dst_ds.SetProjection(wkt)
    dst_ds.SetGeoTransform(src_ds.GetGeoTransform())

    dstband = dst_ds.GetRasterBand(1)

    # Parameters
    prog_func = None
    threshold = 4
    connectedness = 8

    result = gdal.SieveFilter(mem_band,
                              maskband,
                              dstband,
                              threshold,
                              connectedness,
                              callback=prog_func)

    sieved = dstband.ReadAsArray()
    sieved[sieved < 0] = 0

    src_new = gdal.Open(image)
    out_img = src_new.ReadAsArray().astype(np.float)

    out_img[np.isnan(out_img)] = 0

    for b in range(out_img.shape[0]):
        out_img[b, :, :][sieved == 0] = 0

    dst_full = dst_filename.split('.')[0] + '_full.tif'

    save_raster(out_img, image, dst_full, convdate)
    sys.exit()
예제 #5
0
def ClumpEliminate(rasterPath, neighbors, pxSize):
    drvMemR = gdal.GetDriverByName('MEM')
    # Output is a raster that is written into memory
    ds = gdal.Open(rasterPath)
    gt = ds.GetGeoTransform()
    pr = ds.GetProjection()
    cols = ds.RasterXSize
    rows = ds.RasterYSize
    # Generate output-file --> first in memory
    sieveMem = drvMemR.Create('', cols, rows, 1, gdal.GDT_Byte)
    sieveMem.SetGeoTransform(gt)
    sieveMem.SetProjection(pr)
    # Do the ClumpSieve
    rb_in = ds.GetRasterBand(1)
    rb_out = sieveMem.GetRasterBand(1)
    maskband = None
    prog_func = gdal.TermProgress
    result = gdal.SieveFilter(rb_in,
                              maskband,
                              rb_out,
                              pxSize,
                              neighbors,
                              callback=prog_func)
    return sieveMem
예제 #6
0
            aspectTemp = np.where(((aspectArray >= 0) & (aspectArray <= 1))|
                            ((aspectArray >= 89) & (aspectArray <= 91))|
                            ((aspectArray >= 179) & (aspectArray <= 181))|
                            ((aspectArray >= 269) & (aspectArray <= 271))|
                            ((aspectArray >= 359) & (aspectArray <= 360))
                            ,0,255)

            ssTemp = np.where((srcArray == srcNoDataValue) |
                              ((srcArray <= valueRange[0]) & (srcArray >= valueRange[1])) |
                              (slopeArray >= slopeThreshold)
                              ,0,255)

            aspectBand.WriteArray(aspectTemp ,colstep * 1024, rowstep * 1024)
            resultBand.WriteArray(ssTemp ,colstep * 1024, rowstep * 1024)

    gdal.SieveFilter(srcBand=aspectBand, maskBand=None, dstBand=aspectBand, threshold=(512))
    for rowstep in range(rowblockNum):
        for colstep in range(colblockNum):
            rowpafNum = 1024
            colpafNum = 1024
            if (rowstep == rowblockNum - 1):
                rowpafNum = int((rowNum - 1) % 1024) + 1
            if (colstep == colblockNum - 1):
                colpafNum = int((columnNum - 1) % 1024) + 1

            resultArray = resultBand.ReadAsArray(colstep * 1024, rowstep * 1024, colpafNum, rowpafNum)
            aspectArray = aspectBand.ReadAsArray(colstep * 1024, rowstep * 1024, colpafNum, rowpafNum)
            resultTemp = np.where(aspectArray == 0, 0, resultArray)
            resultBand.WriteArray(resultTemp, colstep * 1024, rowstep * 1024)

    dstLayername = "POLYGONIZED"
예제 #7
0
def CreateMaxMinIce(inpath, outfilepath, landmask_raster,
                    coastalerrormask_raster, oceanmask_buffer5,
                    NSIDC_balticmask):
    ''' 
         Creates maximum and minimum ice map, GeoTIFF and shapefile
         maximum = at least one day ice at this pixel
         minimum = every day ice at this pixel
         In addition a file simply giving the number of days with ice
         
         The poly shapefile has all features as polygon, the line shapefile
         only the max or min ice edge
    
    '''

    #register all gdal drivers
    gdal.AllRegister()

    # Iterate through all rasterfiles
    # filelist is all GeoTIFF files created in outfilepath
    filelist = glob.glob(outfilepath + 'nt*.tif')

    #Determine Number of Days from available ice chart files
    NumberOfDays = len(filelist)

    #Files are all the same properties, so take first one to get info
    firstfilename = filelist[0]

    #Define file names
    (infilepath, infilename) = os.path.split(
        firstfilename)  #get path and filename seperately
    (infileshortname, extension) = os.path.splitext(infilename)

    outfile = inpath + 'icechart_NumberOfDays' + os.path.split(
        filelist[0])[1][3:9] + '_' + os.path.split(
            filelist[-1])[1][3:9] + '.tif'
    outfilemax = inpath + 'icechart_maximum' + os.path.split(
        filelist[0])[1][3:9] + '_' + os.path.split(
            filelist[-1])[1][3:9] + '.tif'
    outfilemin = inpath + 'icechart_minimum' + os.path.split(
        filelist[0])[1][3:9] + '_' + os.path.split(
            filelist[-1])[1][3:9] + '.tif'

    outshape_polymax = inpath + 'icechart_poly_maximum' + os.path.split(
        filelist[0])[1][3:9] + '_' + os.path.split(
            filelist[-1])[1][3:9] + '.shp'
    outshape_polymin = inpath + 'icechart_poly_minimum' + os.path.split(
        filelist[0])[1][3:9] + '_' + os.path.split(
            filelist[-1])[1][3:9] + '.shp'
    outshape_linemax = inpath + 'icechart_line_maximum' + os.path.split(
        filelist[0])[1][3:9] + '_' + os.path.split(
            filelist[-1])[1][3:9] + '.shp'
    outshape_linemin = inpath + 'icechart_line_minimum' + os.path.split(
        filelist[0])[1][3:9] + '_' + os.path.split(
            filelist[-1])[1][3:9] + '.shp'

    #Temporary shapefile, all subfiles specified so that they can be removed later
    #Many because gdal commands expect existing files
    outshape_tempmax = inpath + 'icechart_tempmax.shp'
    outshape_tempmax2 = inpath + 'icechart_tempmax.dbf'
    outshape_tempmax3 = inpath + 'icechart_tempmax.prj'
    outshape_tempmax4 = inpath + 'icechart_tempmax.shx'
    outshape_tempmin = inpath + 'icechart_tempmin.shp'
    outshape_tempmin2 = inpath + 'icechart_tempmin.dbf'
    outshape_tempmin3 = inpath + 'icechart_tempmin.prj'
    outshape_tempmin4 = inpath + 'icechart_tempmin.shx'

    outshape_temp2max = inpath + 'icechart_temp2max.shp'
    outshape_temp2max2 = inpath + 'icechart_temp2max.dbf'
    outshape_temp2max3 = inpath + 'icechart_temp2max.prj'
    outshape_temp2max4 = inpath + 'icechart_temp2max.shx'
    outshape_temp2min = inpath + 'icechart_temp2min.shp'
    outshape_temp2min2 = inpath + 'icechart_temp2min.dbf'
    outshape_temp2min3 = inpath + 'icechart_temp2min.prj'
    outshape_temp2min4 = inpath + 'icechart_temp2min.shx'

    outshape_temp3max = inpath + 'icechart_temp3max.shp'
    outshape_temp3max2 = inpath + 'icechart_temp3max.dbf'
    outshape_temp3max3 = inpath + 'icechart_temp3max.prj'
    outshape_temp3max4 = inpath + 'icechart_temp3max.shx'
    outshape_temp3min = inpath + 'icechart_temp3min.shp'
    outshape_temp3min2 = inpath + 'icechart_temp3min.dbf'
    outshape_temp3min3 = inpath + 'icechart_temp3min.prj'
    outshape_temp3min4 = inpath + 'icechart_temp3min.shx'

    ########
    # CREATE NUMBER OF DAYS RASTER FILE AS COPY FROM ICE FILE
    ########
    #open the IceChart
    icechart = gdal.Open(firstfilename, gdalconst.GA_ReadOnly)
    if firstfilename is None:
        print 'Could not open ', firstfilename
        return
    #get image size
    rows = icechart.RasterYSize
    cols = icechart.RasterXSize
    #create output images
    driver = icechart.GetDriver()
    outraster = driver.Create(outfile, cols, rows, 1, gdal.GDT_Float64)
    if outraster is None:
        print 'Could not create ', outfile
        return

    outrastermax = driver.Create(outfilemax, cols, rows, 1, gdal.GDT_Float64)
    if outrastermax is None:
        print 'Could not create ', outfilemax
        return

    outrastermin = driver.Create(outfilemin, cols, rows, 1, gdal.GDT_Float64)
    if outrastermin is None:
        print 'Could not create ', outfilemin
        return

    # Set Geotransform and projection for outraster
    outraster.SetGeoTransform(icechart.GetGeoTransform())
    outraster.SetProjection(icechart.GetProjection())
    outrastermax.SetGeoTransform(icechart.GetGeoTransform())
    outrastermax.SetProjection(icechart.GetProjection())

    outrastermin.SetGeoTransform(icechart.GetGeoTransform())
    outrastermin.SetProjection(icechart.GetProjection())

    rows = outrastermax.RasterYSize
    cols = outrastermax.RasterXSize
    raster = numpy.zeros((rows, cols), numpy.float)

    outraster.GetRasterBand(1).WriteArray(raster)
    outrastermax.GetRasterBand(1).WriteArray(raster)
    outrastermin.GetRasterBand(1).WriteArray(raster)

    #Create output array and fill with zeros
    outarray = numpy.zeros((rows, cols), numpy.float)
    outarraymax = numpy.zeros((rows, cols), numpy.float)
    outarraymin = numpy.zeros((rows, cols), numpy.float)

    #######
    # CALCULATE NUMBER OF DAYS RASTER = NUMBER SAYS HOW MANY DAYS ICE IN PIXEL
    #######
    #Loop through all files to do calculation
    for infile in filelist:

        (infilepath, infilename) = os.path.split(infile)
        print 'Processing ', infilename

        #open the IceChart
        icechart = gdal.Open(infile, gdalconst.GA_ReadOnly)
        if infile is None:
            print 'Could not open ', infilename
            return

        #Read input raster into array
        iceraster = icechart.ReadAsArray()

        #Array calculation -- if ice > 15% count additional day, otherwise keep value
        outarray = numpy.where((iceraster >= 38), outarray + 1, outarray)

        #Clear iceraster for next loop -- just in case
        iceraster = None

    #outarray contains now NumberOfDay with ice -- burn in landmask
    landmask = gdal.Open(landmask_raster, gdalconst.GA_ReadOnly)
    landraster = landmask.ReadAsArray()
    outarray = numpy.where((landraster == 251), 251, outarray)
    outarray = numpy.where((landraster == 252), 252, outarray)
    outarray = numpy.where((landraster == 253), 253, outarray)
    outarray = numpy.where((landraster == 254), 254, outarray)
    outarray = numpy.where((landraster == 255), 255, outarray)

    #######
    # CALCULATE MAXIMUM RASTER
    #######
    # Where never was ice, set map to 0, elsewhere to 1, i.e. at least one day ice
    # Using landraster again -- otherwise if NumberOfDay mask by chance 252, it is masked out
    outarraymax = numpy.where((outarray == 0), 0, 1)
    outarraymax = numpy.where((landraster == 251), 251, outarraymax)
    outarraymax = numpy.where((landraster == 252), 252, outarraymax)
    outarraymax = numpy.where((landraster == 253), 253, outarraymax)
    outarraymax = numpy.where((landraster == 254), 254, outarraymax)
    outarraymax = numpy.where((landraster == 255), 255, outarraymax)

    #######
    # CALCULATE MINIMUM RASTER
    #######
    # Where every day was ice, set to 1, otherwise to 0
    # Keep in mind: Problems may arise when one value is missing (bad file)
    # such that value is just one or two less than NumberofDays
    outarraymin = numpy.where((outarray == NumberOfDays), 1, 0)
    outarraymin = numpy.where((landraster == 251), 251, outarraymin)
    outarraymin = numpy.where((landraster == 252), 252, outarraymin)
    outarraymin = numpy.where((landraster == 253), 253, outarraymin)
    outarraymin = numpy.where((landraster == 254), 254, outarraymin)
    outarraymin = numpy.where((landraster == 255), 255, outarraymin)

    #get the bands
    outband = outraster.GetRasterBand(1)
    outbandmax = outrastermax.GetRasterBand(1)
    outbandmin = outrastermin.GetRasterBand(1)

    #Write all arrays to file

    outband.WriteArray(outarray)
    outband.FlushCache()

    outbandmax.WriteArray(outarraymax)
    outbandmax.FlushCache()

    outbandmin.WriteArray(outarraymin)
    outbandmin.FlushCache()

    ##########
    # FILTER NOISE IN MINIMUM ARRAY / RASTER
    #########
    # the sieve filter takes out singular "islands" of pixels
    srcband = outbandmin
    dstband = outbandmin
    maskband = None
    print "Apply SieveFilter on ", outfilemin
    gdal.SieveFilter(srcband, maskband, dstband, threshold=3, connectedness=4)
    #load outbandmin once more and burn landmask again since sieve influences coastline
    outarraymin = outrastermin.ReadAsArray()
    outarraymin = numpy.where((landraster == 251), 251, outarraymin)
    outarraymin = numpy.where((landraster == 252), 252, outarraymin)
    outarraymin = numpy.where((landraster == 253), 253, outarraymin)
    outarraymin = numpy.where((landraster == 254), 254, outarraymin)
    outarraymin = numpy.where((landraster == 255), 255, outarraymin)
    outbandmin = outrastermin.GetRasterBand(1)
    outbandmin.WriteArray(outarraymin)
    outbandmin.FlushCache()

    ##########
    # FILTER NOISE IN MINIMUM ARRAY / RASTER
    #########
    # the sieve filter takes out singular "islands" of pixels
    srcband = outbandmax
    dstband = outbandmax
    maskband = None
    print "Apply SieveFilter one ", outrastermax
    gdal.SieveFilter(srcband, maskband, dstband, threshold=3, connectedness=4)
    #load outbandmin once more and burn landmask again since sieve influences coastline
    outarraymax = outrastermax.ReadAsArray()
    outarraymax = numpy.where((landraster == 251), 251, outarraymax)
    outarraymax = numpy.where((landraster == 252), 252, outarraymax)
    outarraymax = numpy.where((landraster == 253), 253, outarraymax)
    outarraymax = numpy.where((landraster == 254), 254, outarraymax)
    outarraymin = numpy.where((landraster == 255), 255, outarraymin)
    outbandmax = outrastermax.GetRasterBand(1)
    outbandmax.WriteArray(outarraymax)
    outbandmax.FlushCache()

    #Clear arrays and close files
    outband = None
    outbandmax = None
    outbandmin = None
    iceraster = None
    outraster = None
    outrastermax = None
    outrastermin = None
    outarray = None
    outarraymax = None
    outarraymin = None
    landraster = None
    landmask = None

    ###################
    # CONVERT THE RASTERS CREATED ABOVE TO SHAPEFILES
    ###################

    # conversion to shape
    print '\n Convert ', outfilemax, ' to shapefile.'
    os.system('gdal_polygonize.py ' + outfilemax + ' -f "ESRI Shapefile" ' +
              outshape_tempmax)
    print '\n Convert ', outfilemin, ' to shapefile.'
    os.system('gdal_polygonize.py ' + outfilemin + ' -f "ESRI Shapefile" ' +
              outshape_tempmin)

    # FILTERING MAX / MIN
    # Get the large polygon only, this removes mistaken areas at coast and noise. KEEP IN MIND: CHECK VALUE IF TOO BIG SUCH THAT REAL AREAS ARE REMOVED
    # Do this only for polymax -- the minimum would remove real areas, patches like East of Svalbard. Polymin selects here all polygons basically
    print "Select large polygon, ignoring the small ones"
    os.system(
        'ogr2ogr -progress ' + outshape_polymax + ' ' + outshape_tempmax +
        ' -sql "SELECT *, OGR_GEOM_AREA FROM icechart_tempmax WHERE DN=1 AND OGR_GEOM_AREA > 10000000000.0"'
    )
    os.system(
        'ogr2ogr -progress ' + outshape_polymin + ' ' + outshape_tempmin +
        ' -sql "SELECT *, OGR_GEOM_AREA FROM icechart_tempmin WHERE DN=1 AND OGR_GEOM_AREA > 10.0"'
    )

    # Convert polygon to lines
    print 'Convert ice edge map to Linestring Map'
    os.system('ogr2ogr -progress -nlt LINESTRING -where "DN=1" ' +
              outshape_temp2max + ' ' + outshape_polymax)
    os.system('ogr2ogr -progress -nlt LINESTRING -where "DN=1" ' +
              outshape_temp2min + ' ' + outshape_polymin)

    # Remove coast line from ice edge by clipping with coastline
    # Prerequisite: Create NISDC coast line mask ( ogr2ogr -progress C:\Users\max\Desktop\NSIDC_oceanmask.shp C:\Users \max\Desktop\temp.shp
    # -sql "SELECT *, OGR_GEOM_AREA FROM temp WHERE DN<250 )
    # use "dissolve" to get ocean only with one value and the run buffer -5000m such that coast line does not match but overlaps ice polygon
    # because only then it is clipped
    os.system('ogr2ogr -progress -clipsrc ' + oceanmask_buffer5 + ' ' +
              outshape_linemax + ' ' + outshape_temp2max)
    os.system('ogr2ogr -progress -clipsrc ' + oceanmask_buffer5 + ' ' +
              outshape_linemin + ' ' + outshape_temp2min)

    #Cleaning up temporary files
    os.remove(outshape_tempmax)
    os.remove(outshape_tempmax2)
    os.remove(outshape_tempmax3)
    os.remove(outshape_tempmax4)
    os.remove(outshape_tempmin)
    os.remove(outshape_tempmin2)
    os.remove(outshape_tempmin3)
    os.remove(outshape_tempmin4)
    os.remove(outshape_temp2max)
    os.remove(outshape_temp2max2)
    os.remove(outshape_temp2max3)
    os.remove(outshape_temp2max4)
    os.remove(outshape_temp2min)
    os.remove(outshape_temp2min2)
    os.remove(outshape_temp2min3)
    os.remove(outshape_temp2min4)

    ##########
    # ADDING BALTIC SEA
    ##########

    #Treated separatedly since close to coast and therefore sensitive to coastal errors
    print '\n Add Baltic Sea Ice.'

    #polygonice only Baltic Sea
    os.system('gdal_polygonize.py ' + outfilemax + ' -mask ' +
              NSIDC_balticmask + ' -f "ESRI Shapefile" ' + outshape_tempmax)
    os.system('gdal_polygonize.py ' + outfilemin + ' -mask ' +
              NSIDC_balticmask + ' -f "ESRI Shapefile" ' + outshape_tempmin)

    # Add Baltic to existing polymax and polymin
    os.system(
        'ogr2ogr -update -append ' + outshape_polymax + ' ' +
        outshape_tempmax +
        ' -sql "SELECT *, OGR_GEOM_AREA FROM icechart_tempmax WHERE DN=1 AND OGR_GEOM_AREA > 20000000000.0"'
    )
    os.system(
        'ogr2ogr -update -append ' + outshape_polymin + ' ' +
        outshape_tempmin +
        ' -sql "SELECT *, OGR_GEOM_AREA FROM icechart_tempmin WHERE DN=1"')

    # Convert polygon to lines
    print 'Convert ice edge map to Linestring Map'
    os.system('ogr2ogr -progress -nlt LINESTRING -where "DN=1" ' +
              outshape_temp2max + ' ' + outshape_polymax)
    os.system('ogr2ogr -progress -nlt LINESTRING -where "DN=1" ' +
              outshape_temp2min + ' ' + outshape_polymin)

    #clip coast as above
    os.system('ogr2ogr -progress -clipsrc ' + oceanmask_buffer5 + ' ' +
              outshape_temp3max + ' ' + outshape_temp2max)
    os.system('ogr2ogr -progress -clipsrc ' + oceanmask_buffer5 + ' ' +
              outshape_temp3min + ' ' + outshape_temp2min)

    # Add Baltic line to existing min/max line
    os.system('ogr2ogr -update -append ' + outshape_linemax + ' ' +
              outshape_temp3max)
    os.system('ogr2ogr -update -append ' + outshape_linemin + ' ' +
              outshape_temp3min)

    #########
    # REDO MAX MIN RASTER
    #########

    #The polygon and line files are now cleaned for noise since only large polygon
    # was chosen for minimum polygon
    # Re-rasterize to tif, such that the tiff is also cleaned

    # gdal rasterize should be able to overwrite / create new a file. Since this does not work, I set the
    # existing one to zero and rasterize the polgon into it
    print 'Rerasterize max and min GeoTIFF'
    outarray = gdal.Open(outfilemax, gdalconst.GA_Update)
    outarraymax = outarray.ReadAsArray()
    outarraymax = numpy.zeros((rows, cols), numpy.float)
    outbandmax = outarray.GetRasterBand(1)
    outbandmax.WriteArray(outarraymax)
    outbandmax.FlushCache()
    outarray = None

    #Rasterize polygon

    os.system('gdal_rasterize -burn 1 ' + outshape_polymax + ' ' + outfilemax)
    # OPen raster and burn in landmask again -- is not contained in polygon
    outarray = gdal.Open(outfilemax, gdalconst.GA_Update)
    outarraymax = outarray.ReadAsArray()
    landmask = gdal.Open(landmask_raster, gdalconst.GA_ReadOnly)
    landraster = landmask.ReadAsArray()
    outarraymax = numpy.where((landraster == 251), 251, outarraymax)
    outarraymax = numpy.where((landraster == 252), 252, outarraymax)
    outarraymax = numpy.where((landraster == 253), 253, outarraymax)
    outarraymax = numpy.where((landraster == 254), 254, outarraymax)
    outarraymax = numpy.where((landraster == 255), 255, outarraymax)
    outbandmax = outarray.GetRasterBand(1)
    outbandmax.WriteArray(outarraymax)
    outbandmax.FlushCache()
    outarray = None
    landmask = None
    landraster = None

    #Reraster the min image
    outarray = gdal.Open(outfilemin, gdalconst.GA_Update)
    outarraymin = outarray.ReadAsArray()
    outarraymin = numpy.zeros((rows, cols), numpy.float)
    outbandmin = outarray.GetRasterBand(1)
    outbandmin.WriteArray(outarraymin)
    outbandmin.FlushCache()
    outarray = None
    #Rasterize polygon
    os.system('gdal_rasterize -burn 1 ' + outshape_polymin + ' ' + outfilemin)
    # OPen raster and burn in landmask again -- is not contained in polygon
    outarray = gdal.Open(outfilemin, gdalconst.GA_Update)
    outarraymin = outarray.ReadAsArray()
    landmask = gdal.Open(landmask_raster, gdalconst.GA_ReadOnly)
    landraster = landmask.ReadAsArray()
    outarraymin = numpy.where((landraster == 251), 251, outarraymin)
    outarraymin = numpy.where((landraster == 252), 252, outarraymin)
    outarraymin = numpy.where((landraster == 253), 253, outarraymin)
    outarraymin = numpy.where((landraster == 254), 254, outarraymin)
    outarraymin = numpy.where((landraster == 255), 255, outarraymin)
    outbandmin = outarray.GetRasterBand(1)
    outbandmin.WriteArray(outarraymin)
    outbandmin.FlushCache()
    landmask = None
    landraster = None

    #Cleaning up temporary files
    os.remove(outshape_tempmax)
    os.remove(outshape_tempmax2)
    os.remove(outshape_tempmax3)
    os.remove(outshape_tempmax4)
    os.remove(outshape_tempmin)
    os.remove(outshape_tempmin2)
    os.remove(outshape_tempmin3)
    os.remove(outshape_tempmin4)
    os.remove(outshape_temp2max)
    os.remove(outshape_temp2max2)
    os.remove(outshape_temp2max3)
    os.remove(outshape_temp2max4)
    os.remove(outshape_temp2min)
    os.remove(outshape_temp2min2)
    os.remove(outshape_temp2min3)
    os.remove(outshape_temp2min4)
    os.remove(outshape_temp3max)
    os.remove(outshape_temp3max2)
    os.remove(outshape_temp3max3)
    os.remove(outshape_temp3max4)
    os.remove(outshape_temp3min)
    os.remove(outshape_temp3min2)
    os.remove(outshape_temp3min3)
    os.remove(outshape_temp3min4)

    #Reproject to EPSG:3575
    ReprojectShapefile(outshape_polymax)
    ReprojectShapefile(outshape_polymin)
    ReprojectShapefile(outshape_linemax)
    ReprojectShapefile(outshape_linemin)

    #reproject to EPSG3575
    EPSG3411_2_EPSG3575(outfilemax)
    EPSG3411_2_EPSG3575(outfilemin)
    EPSG3411_2_EPSG3575(outfile)
    print
    print 'Done Creating Max/Min Maps'
    return outfilemax, outfilemin
예제 #8
0
    #    else:

    learning.prob_pixel_bloc(modelPth, image, 8, probMap,
                             7, blocksize=256, one_class =1)
    
    
    #==============================================================================
    #==============================================================================

    print('sieving change map')
    
    # Have replaced subprocess with api now eliminating the need for sievelist
    noiseRas = gdal.Open(outMap+'.tif', gdal.GA_Update)
    noiseBand = noiseRas.GetRasterBand(1)
    prog_func = gdal.TermProgress
    result = gdal.SieveFilter(noiseBand, None, noiseBand, 4, 4,
                              callback = prog_func)
    
    
    noiseRas.FlushCache()
    noiseRas = None
    noiseBand = None
    result = None
    
    
    print('producing deforest only raster')
    dF = outMap[:-4]+'_DF'
    
    geodata.mask_raster(outMap+'.tif', 1, overwrite=False, 
                        outputIm = dF[:-4])
    
    geodata.mask_raster(probMap+'.tif', 1, overwrite=False, 
예제 #9
0
import gdal
filename = 'final.tif'
output = 'final_clumped.tif'
gdal.AllRegister()
threshold = 200
connectedness = 4
src_ds = gdal.Open(filename, gdal.GA_ReadOnly)
srcband = src_ds.GetRasterBand(1)
maskband = srcband.GetMaskBand()
drv = gdal.GetDriverByName(str('GTiff'))
dst_ds = drv.Create(output,
                    src_ds.RasterXSize,
                    src_ds.RasterYSize,
                    1,
                    srcband.DataType,
                    options=['COMPRESS=LZW'])
wkt = src_ds.GetProjection()
if wkt != '':
    dst_ds.SetProjection(wkt)
dst_ds.SetGeoTransform(src_ds.GetGeoTransform())
dstband = dst_ds.GetRasterBand(1)
prog_func = gdal.TermProgress
result = gdal.SieveFilter(srcband,
                          maskband,
                          dstband,
                          threshold,
                          connectedness,
                          callback=prog_func)
src_ds = None
dst_ds = None
mask_ds = None