def watermask(water_in, radar_in, outName, outShp):
    bandDefns = []
    bandDefns.append(BandDefn('VV', radar_in, 1))
    bandDefns.append(BandDefn('water', water_in, 1))
    gdalformat = 'KEA'
    imagecalc.bandMath(outName, '(VV<-18)&&(water==12)?1:0', gdalformat,
                       rsgislib.TYPE_8UINT, bandDefns)
예제 #2
0
def wetvegmask(water_in, radar_in, outName, outShp):
    bandDefns = []
    bandDefns.append(BandDefn('VVVH', radar_in, 3))
    bandDefns.append(BandDefn('water', water_in, 1))
    gdalformat = 'KEA'
    imagecalc.bandMath(outName, '(VVVH<0.45)&&(water>=2)?1:0', gdalformat,
                       rsgislib.TYPE_8UINT, bandDefns)
예제 #3
0
	def bandMath(inputImageVV,inputImageVH,outputImage):
		gdalformat = 'GTiff'
		datatype = rsgislib.TYPE_32FLOAT
		expression = 'b1/b2'
		bandDefns = []
		bandDefns.append(BandDefn('b1', inputImageVV, 1))
		bandDefns.append(BandDefn('b2', inputImageVH, 1))
		imagecalc.bandMath(outputImage, expression, gdalformat, datatype, bandDefns)
def wetvegmask(water_in, radar_in, outName, outShp):
	print("Reading raster datasets as arrays....")
	# define bands
	bandDefns = []
	bandDefns.append(BandDefn('VVVH', radar_in, 3))
	bandDefns.append(BandDefn('water', water_in, 1))
	# conditional statement to select semi-permanent water with high VV:VH difference 
	print("Running conditional statement....")
	gdalformat = 'KEA'
	imagecalc.bandMath(outName, '(VVVH<0.45)&&(water>=2)?1:0', gdalformat, rsgislib.TYPE_8UINT, bandDefns)
def bandMath(inputImage, outputImage):
    gdalformat = 'GTiff'
    datatype = rsgislib.TYPE_32FLOAT
    expression = '(g-nir)/(g+nir)'
    #	expression = '(nir-r)/(nir+r)'
    bandDefns = []
    bandDefns.append(BandDefn('g', inputImage, 4))
    bandDefns.append(BandDefn('r', inputImage, 3))
    bandDefns.append(BandDefn('nir', inputImage, 2))
    bandDefns.append(BandDefn('swir', inputImage, 1))
    imagecalc.bandMath(outputImage, expression, gdalformat, datatype,
                       bandDefns)
def watermask(water_in, radar_in, outName, outShp):
	print("Reading raster datasets as arrays....")
	
	# define bands
	bandDefns = []
	bandDefns.append(BandDefn('VV', radar_in, 1))
	bandDefns.append(BandDefn('water', water_in, 1))
	
	# conditional statement to select permanent water with low backscatter
	print("Running conditional statement....")
	gdalformat = 'KEA'
	imagecalc.bandMath(outName, '(VV<-18)&&(water==12)?1:0', gdalformat, rsgislib.TYPE_8UINT, bandDefns)
def colour_SM_image(inimage, colourimage, max_value=0.5, band=1):
    """
    Colour image 

    """
    try:
        import rsgislib
        from rsgislib import imagecalc
        from rsgislib.imagecalc import BandDefn
        from rsgislib import rastergis
    except ImportError:
        raise ImportError("Could not import RSGISLib, required"
                          " to colour image")

    if max_value == 0.5:

        # Add class field:
        bandDefns = []
        bandDefns.append(BandDefn('SM', inimage, band))

        expression = []
        expression.append('0.00')
        expression.append('(SM > 0.00) && (SM <= 0.05)? 1 : 0')
        expression.append('(SM > 0.05) && (SM <= 0.10)? 2 : 0')
        expression.append('(SM > 0.10) && (SM <= 0.15)? 3 : 0')
        expression.append('(SM > 0.15) && (SM <= 0.20)? 4 : 0')
        expression.append('(SM > 0.20) && (SM <= 0.25)? 5 : 0')
        expression.append('(SM > 0.25) && (SM <= 0.30)? 6 : 0')
        expression.append('(SM > 0.30) && (SM <= 0.35)? 7 : 0')
        expression.append('(SM > 0.35) && (SM <= 0.40)? 8 : 0')
        expression.append('(SM > 0.40) && (SM <= 0.45)? 9 : 0')
        expression.append('(SM > 0.45) && (SM <= 0.50)? 10 : 0')

        gdalformat = get_gdal_format(colourimage)
        datatype = rsgislib.TYPE_8INT

        temp_dir = tempfile.mkdtemp(prefix='soilscape_upscaling')
        colourbase = os.path.basename(colourimage)
        colourbase, colourext = os.path.splitext(colourbase)
        colour = []
        for i in range(11):
            colour.append(
                os.path.join(temp_dir,
                             "{}_{}{}".format(colourbase, i + 1, colourext)))
            imagecalc.bandMath(colour[i], expression[i], gdalformat, datatype,
                               bandDefns)

        bandDefns = []
        for i in range(11):
            SMclass = 'SM' + str(i)
            bandDefns.append(BandDefn(SMclass, colour[i], 1))
            if i == 0:
                expression = SMclass
            else:
                expression = expression + '+' + SMclass
        imagecalc.bandMath(colourimage, expression, gdalformat, datatype,
                           bandDefns)

        shutil.rmtree(temp_dir)

        # Populate stats (converts to RAT):
        rastergis.populateStats(colourimage, False, False, True, ratband=1)

        # Add class field:
        bandStats = []
        bandStats.append(rastergis.BandAttStats(band=1, maxField="SMclass"))
        rastergis.populateRATWithStats(colourimage,
                                       colourimage,
                                       bandStats,
                                       ratband=1)

        field = 'SMclass'
        classcolours = {}
        colourCat = collections.namedtuple('ColourCat',
                                           ['red', 'green', 'blue', 'alpha'])
        for i in range(11):
            classcolours[i] = colourCat(red=0, green=0, blue=0, alpha=255)
        classcolours[0] = colourCat(red=0, green=0, blue=0, alpha=255)
        classcolours[1] = colourCat(red=165, green=0, blue=38, alpha=255)
        classcolours[2] = colourCat(red=215, green=48, blue=39, alpha=255)
        classcolours[3] = colourCat(red=244, green=109, blue=67, alpha=255)
        classcolours[4] = colourCat(red=253, green=174, blue=97, alpha=255)
        classcolours[5] = colourCat(red=254, green=224, blue=144, alpha=255)
        classcolours[6] = colourCat(red=224, green=243, blue=248, alpha=255)
        classcolours[7] = colourCat(red=171, green=217, blue=233, alpha=255)
        classcolours[8] = colourCat(red=116, green=173, blue=209, alpha=255)
        classcolours[9] = colourCat(red=69, green=117, blue=180, alpha=255)
        classcolours[10] = colourCat(red=49, green=54, blue=149, alpha=255)
        rastergis.colourClasses(colourimage, field, classcolours)

    else:
        raise ValueError('Failed to find colours for specified max_value')
def processSingleFile(inputFile, outputDIR, tmpath, calcExtraBands, palsar2=False):
    inputFile = os.path.abspath(inputFile)
    outputDIR = os.path.abspath(outputDIR)
    tmpath = os.path.abspath(tmpath)
    print("Processing: " + inputFile)
    baseName = os.path.basename(inputFile).split(".")[0]
    print("\t" + baseName)
    rsgisUtils = rsgislib.RSGISPyUtils()
    uidStr = "_"+rsgisUtils.uidGenerator()
    createdTmp = False
    if not os.path.exists(tmpath):
        os.makedirs(tmpath)
        createdTmp = True
    
    extract2DIR = os.path.join(tmpath, baseName+uidStr)
    if not os.path.exists(extract2DIR):
        os.makedirs(extract2DIR)
    os.chdir(extract2DIR)
    
    cmd = 'tar -xzf ' + inputFile
    print(cmd)
    subprocess.call(cmd, shell=True)
    
    try:
        if palsar2:
            hhFiles = glob.glob(os.path.join(extract2DIR, HH_P2_FILE_PATTERN))
            hvFiles = glob.glob(os.path.join(extract2DIR, HV_P2_FILE_PATTERN))
            
            if len(hhFiles) == 0:
                hhFiles = glob.glob(os.path.join(extract2DIR, HH_P2_FP_FILE_PATTERN))
            if len(hvFiles) == 0:
                hvFiles = glob.glob(os.path.join(extract2DIR, HV_P2_FP_FILE_PATTERN))
            
            in_hh_file = hhFiles[0]
            in_hv_file = hvFiles[0]
        else:
            in_hh_file = glob.glob(os.path.join(extract2DIR, HH_P1_FILE_PATTERN))[0]
            in_hv_file = glob.glob(os.path.join(extract2DIR, HV_P1_FILE_PATTERN))[0]
    except IndexError:
        raise Exception('Could not find data - check filenames')
    
    bands_list = [in_hh_file, in_hv_file]
    band_names = ['HH','HV']
    
    # Create extra image bands
    for calcBand in calcExtraBands:    
        if calcBand == 'COVARHH':
            extraBandFile = os.path.join(extract2DIR, baseName + '_covhh.kea')
            imagefilter.applyCoeffOfVarFilter(in_hh_file, extraBandFile, 5, 'KEA', rsgislib.TYPE_32FLOAT)
            bandName = 'CoVHH'
            bands_list.append(extraBandFile)
            band_names.append(bandName)
        if calcBand == 'COVARHV':
            extraBandFile = os.path.join(extract2DIR, baseName + '_covhv.kea')
            imagefilter.applyCoeffOfVarFilter(in_hv_file, extraBandFile, 5, 'KEA', rsgislib.TYPE_32FLOAT)
            bandName = 'CoVHV'
            bands_list.append(extraBandFile)
            band_names.append(bandName)
        if calcBand == 'HHHV':
            extraBandFile = os.path.join(extract2DIR, baseName + '_hhhv.kea')
            bandDefns = [imagecalc.BandDefn('hh', in_hh_file, 1),
                         imagecalc.BandDefn('hv', in_hv_file, 1)]
            imagecalc.bandMath(extraBandFile, 'hv==0?0:hh/hv', 'KEA', rsgislib.TYPE_32FLOAT, bandDefns) 
            bandName = 'HH/HV'
            bands_list.append(extraBandFile)
            band_names.append(bandName)
    
    # Create stack
    stackFile = os.path.join(outputDIR, baseName + '_stack.kea')
    imageutils.stackImageBands(bands_list, band_names, stackFile, None, 0, 'KEA', rsgislib.TYPE_32FLOAT) 
    imageutils.popImageStats(stackFile, usenodataval=True, nodataval=0, calcpyramids=True)
    
    try:
        in_mask_file = glob.glob(os.path.join(extract2DIR, MASK_FILE_PATTERN))[0]
        out_mask_file = os.path.join(outputDIR, baseName + '_mask.kea')
        cmd = 'gdal_translate -of KEA ' + in_mask_file + ' ' + out_mask_file
        subprocess.call(cmd, shell=True)
        rastergis.populateStats(out_mask_file, True, True)
    except IndexError:
        print("WARNING: Could not find the mask file... Ignoring.")
    
    try:
        in_date_file = glob.glob(os.path.join(extract2DIR, DATE_FILE_PATTERN))[0]
        out_date_file = os.path.join(outputDIR, baseName + '_date.kea')
        cmd = 'gdal_translate -of KEA ' + in_date_file + ' ' + out_date_file
        subprocess.call(cmd, shell=True)
        rastergis.populateStats(out_date_file, True, True)
    except IndexError:
        print("WARNING: Could not find the date file... Ignoring.")
        
    try:
        in_linci_file = glob.glob(os.path.join(extract2DIR, LINCI_FILE_PATTERN))[0]
        out_linci_file = os.path.join(outputDIR, baseName + '_linci.kea')
        cmd = 'gdal_translate -of KEA ' + in_linci_file + ' ' + out_linci_file
        subprocess.call(cmd, shell=True)
        rastergis.populateStats(out_linci_file, True, True)
    except IndexError:
        print("WARNING: Could not find the linci file... Ignoring.")
    
    shutil.rmtree(extract2DIR)
    if createdTmp:
        shutil.rmtree(tmpath)
예제 #9
0
bandDefns.append(BandDefn('b20171219', inputImage, 23))
bandDefns.append(BandDefn('b20171231', inputImage, 24))

datatype = rsgislib.TYPE_8UINT
gdalformat = 'KEA'

print('')
print('Creating water/non-water masks')
print('It took {0:0.1f} minutes'.format((time.time() - start) / 60))
# expression to give water (1) and no water (0) per date
for band in bandNames[0:2]:
    expression = ''
    expression += '(' + band + '==1) || (' + band + '==3) '  # select veg or open water
    expression += '?1:0'  # if true give value of 1, else 0
    outputImage = band + '_water.kea'
    imagecalc.bandMath(outputImage, expression, gdalformat, datatype,
                       bandDefns)

# print out all the various bandDefns functions
#for b in bandNames:
#	band='"'+b+'"'
#	img=b+'_water.kea'
#	#bandDefns.append(BandDefn(band, inputImage, num))
#	print("bandDefns.append(BandDefn("+band+"," + img + ','+str(1)+"))")
print('')
print('Reading in the masks')
print('It took {0:0.1f} minutes'.format((time.time() - start) / 60))
bandDefns.append(BandDefn("b20170105", b20170105_water.kea, 1))
bandDefns.append(BandDefn("b20170117", b20170117_water.kea, 1))
bandDefns.append(BandDefn("b20170129", b20170129_water.kea, 1))
bandDefns.append(BandDefn("b20170222", b20170222_water.kea, 1))
bandDefns.append(BandDefn("b20170306", b20170306_water.kea, 1))
#		print("Running conditional statement....")
#		gdalformat = 'KEA'
#		imagecalc.bandMath(outName, '(VV<-15)?1:0', gdalformat, rsgislib.TYPE_8UINT, bandDefns)
#
#	outName=radar_in.replace('.tif','_sel_lt15dB.kea')
#
#	high_dB(radar_in, outName)

listFiles = glob.glob('*sel_lt15dB.kea')
listFiles = sorted(listFiles)

bandDefns = []

for img in listFiles:
    band = band = '"' + img.split('.')[0] + '"'
    bandDefns.append(BandDefn(band, img, 1))

expression = '(' + listFiles[0].split('.')[0]
for img in listFiles[1:len(listFiles)]:
    expression += ' + '
    expression += img.split('.')[0]

expression += ') / ' + str(len(listFiles))

gdalformat = 'KEA'
imagecalc.bandMath(outName, expression, gdalformat, rsgislib.TYPE_8UINT,
                   bandDefns)
imagecalc.bandMath(
    outName,
    '(S1B_IW_GRDH_1SDV_20170105T165713_Sigma0_stack_lee_sel_lt15dB.kea + S1B_IW_GRDH_1SDV_20170117T165713_Sigma0_stack_lee_sel_lt15dB.kea + S1B_IW_GRDH_1SDV_20170129T165713_Sigma0_stack_lee_sel_lt15dB.kea) / 3',
    gdalformat, rsgislib.TYPE_8UINT, bandDefns)
예제 #11
0
                    print(gdalrastcmd_HiA)
                    subprocess.call(gdalrastcmd_HiA, shell=True)

                # stretch image to byte 8-bit by linear MinMax
                imageutils.stretchImage(outND4, outND4_s, False, '', False,
                                        True, 'GTiff', rsgislib.TYPE_8INT,
                                        imageutils.STRETCH_LINEARMINMAX)

                # do the same for DTMs

                datatype = rsgislib.TYPE_32FLOAT
                expression = 'b1+9999'
                bandDefns = []
                bandDefns.append(BandDefn('b1', outDTM, 1))

                imagecalc.bandMath(outDTM_a, expression, 'GTiff', datatype,
                                   bandDefns)
                imagecalc.imageStats(outDTM_a, statsDTM, True)

                if not (MGSmode):
                    # LnK
                    datatype = rsgislib.TYPE_32FLOAT
                    minLnKH = 12.0
                    expression = 'max(b1, {m}) - {m}'.format(m=minLnKH)
                    bandDefns = []
                    bandDefns.append(BandDefn('b1', rastVecPolysLnK, 1))
                    imagecalc.bandMath(rastVecPolysLnK_a, expression, 'GTiff',
                                       datatype, bandDefns)
                    imagecalc.imageStats(rastVecPolysLnK_a, statsLnKHead, True)

                imageutils.stretchImage(outDTM_a, outDTM_s, False, '', True,
                                        True, 'GTiff', rsgislib.TYPE_8INT,
#		gdalformat = 'KEA'
#		imagecalc.bandMath(outName, '(VV<-15)?1:0', gdalformat, rsgislib.TYPE_8UINT, bandDefns)
#
#	outName=radar_in.replace('.tif','_sel_lt15dB.kea')
#
#	high_dB(radar_in, outName)

listFiles = glob.glob('*sel_lt15dB_snapped.kea')
listFiles = sorted(listFiles)

bandNum = list(range(1, len(listFiles) + 1))
bands = []
for n in bandNum:
    bands.append('b' + str(n))

bandDefns = []

for b, img in zip(bands, listFiles):
    bandDefns.append(BandDefn(b, img, 1))

expression = '((b1'
for b in bands[1:len(bands)]:
    expression += ' + '
    expression += b

expression += ') / ' + str(len(bands)) + ') * 100'

gdalformat = 'KEA'
imagecalc.bandMath(outName, expression, gdalformat, rsgislib.TYPE_8UINT,
                   bandDefns)
os.system(cmd)
cmd = 'gdal_calc.py -A %s --A_band=3 --outfile=%s --calc="nan_to_num(A)"' % (
    inputImage, b3)
os.system(cmd)

gdalformat = 'KEA'

# define the output names
b1_nan = b1.replace('.kea', '_b1_nan.kea')
b2_nan = b2.replace('.kea', '_b2_nan.kea')
b3_nan = b3.replace('.kea', '_b3_nan.kea')

# band math yto convert zero values to 50
bandDefns = []
bandDefns.append(BandDefn('b1', b1, 1))
imagecalc.bandMath(b1_nan, '(b1==0.0)?50:b1', gdalformat,
                   rsgislib.TYPE_32FLOAT, bandDefns)
bandDefns = []
bandDefns.append(BandDefn('b2', b2, 1))
imagecalc.bandMath(b2_nan, '(b2==0.0)?50:b2', gdalformat,
                   rsgislib.TYPE_32FLOAT, bandDefns)
bandDefns = []
bandDefns.append(BandDefn('b3', b3, 1))
imagecalc.bandMath(b3_nan, '(b3==0.0)?50:b3', gdalformat,
                   rsgislib.TYPE_32FLOAT, bandDefns)

# stack the nonan bands together
gdalformat = 'GTiff'
gdaltype = rsgislib.TYPE_32FLOAT
imageutils.stackImageBands([b1_nan, b2_nan, b3_nan], ['VV', 'VH', 'VVdivVH'],
                           nanOut, None, 50, gdalformat, gdaltype)
gdalformat = 'KEA'
rsgislib.imageutils.resampleImage2Match(inRefImg, inProcessImg, outSnap, gdalformat,interpMethod='nearestneighbour', datatype=rsgislib.TYPE_8UINT)


####################################################################
# add permanent water mask
permWaterMask=outSnap

bandDefns = []
bandDefns.append(BandDefn('class', outCert, 1))
bandDefns.append(BandDefn('permWat', permWaterMask, 1))

condition='(permWat==1)?1:class'

gdalformat = 'kea'
imagecalc.bandMath(outimage, condition, gdalformat, rsgislib.TYPE_8UINT, bandDefns)

# remove the intermediate certainty classifcation image
try:
	os.remove(outCert)
except Exception:
	pass

###########################################################################################
# select dry season images and apply refinement
d=int(inputImage.split('/')[-1].split('_')[4][4:6])

if (d >= 2) & (d <= 6): # select dry season images based on image month
	print('')
	print('Finished...')
	print('')
slope='/Users/Andy/Documents/Zambia/FloodModelling/Data/DEMs/SRTM/barotse_srtm_5x5_slope.tif'
hand='/Users/Andy/Documents/Zambia/FloodModelling/HAND/GEE_hand/hand90_1000.tif'

outShp='/Users/Andy/Documents/Zambia/RemoteSensing/WB_classification/Supporting_data/global_surface_water/barotseland_srtm_utm_lee_slope_gt1_5_wgs84.shp'
outShp2='/Users/Andy/Documents/Zambia/RemoteSensing/WB_classification/Supporting_data/global_surface_water/barotseland_srtm_utm_lee_slope_gt1_5_wgs84_pxl1.shp'


#  snapping 
slopeSnap='/Users/Andy/Documents/Zambia/FloodModelling/Data/DEMs/SRTM/srtm_arc1_barotseland_5x5_slope_snap.kea'
inRefImg=hand # base raster to snap to
gdalFormat = 'KEA'
#rsgislib.imageutils.resampleImage2Match(inRefImg, slope, slopeSnap, gdalFormat, interpMethod='nearestneighbour', datatype=None) # perform resampling/snap

bandDefns = []
bandDefns.append(BandDefn('slope', slopeSnap, 1))
bandDefns.append(BandDefn('hand', hand, 1))

outName='/Users/Andy/Documents/Zambia/FloodModelling/Data/DEMs/SRTM/srtm_arc1_barotseland_5x5_slope_gt3_and_hand_gt30.kea'

gdalformat = 'KEA'
imagecalc.bandMath(outName, '(slope>3)&&(hand>30)&&(hand<1000)?1:0', gdalformat, rsgislib.TYPE_8UINT, bandDefns)

# option to vectorize the output
inputImg=outName

rsgislib.vectorutils.polygoniseRaster(inputImg, outShp, imgBandNo=1, maskImg=None, imgMaskBandNo=1)

cmd="ogr2ogr -where PXLVAL='1' '%s' '%s'" %(outShp,outShp2) 
subprocess.call(cmd, shell=True)
예제 #16
0
                             colType=gdal.GFT_String)

        # export rat column: mode with certainty to image

        gdalformat = 'GTiff'
        datatype = rsgislib.TYPE_8INT
        fields = ['OutClass_mode_cert_sel']

        rastergis.exportCols2GDALImage(clumps, outImage, gdalformat, datatype,
                                       fields)

        #bandmath to add permananent water pixels
        bandDefns = []
        bandDefns.append(BandDefn('class', outImage, 1))
        bandDefns.append(BandDefn('permWater', waterPerm, 1))
        imagecalc.bandMath(outImage, '(permWater>=5)?1:class', 'GTiff',
                           rsgislib.TYPE_8UINT, bandDefns)

        ratDataset = None
        #	clumps=None

        # add colourtable
        #cmd='gdaldem color-relief ' + outImage + ' /Users/Andy/Documents/Zambia/RemoteSensing/WB_classification/gdaldem_wb_class_colours.txt ' + outImage
        #subprocess.call(cmd)
        os.system('afplay /System/Library/Sounds/Tink.aiff')
    except Exception:
        print('')
        print('............................................')
        print('Failed: ' + clumps)
        print('............................................')
        print('')
        pass
#ls_image='/Users/Andy/Documents/Zambia/RemoteSensing/Sentinel_2/GEE/S2_composite_aug_sep_2017_swir_snapped.tif'
sel = '/Users/Andy/Documents/Zambia/RemoteSensing/WB_classification/Supporting_data/sand_exclusion_layer/S1B_IW_GRDH_1SDV_2017_sel_2.kea'

outName = '/Users/Andy/Documents/Zambia/RemoteSensing/WB_classification/Supporting_data/sand_exclusion_layer/sel_hand_sand_mask.kea'

bandDefns = []
#bandDefns.append(BandDefn('water', seasonality, 1))
bandDefns.append(BandDefn('hand', hand, 1))
#bandDefns.append(BandDefn('ndvi', ndvi, 1))
#bandDefns.append(BandDefn('swir', ls_image, 1))
bandDefns.append(BandDefn('sel', sel, 1))
# conditional statement to select semi-permanent water with high VV:VH difference
print("Running conditional statement....")
gdalformat = 'KEA'
#imagecalc.bandMath(outName, '(ndvi>0.06)&&(ndvi<=0.12)&&(water==0)&&(hand>5)&&(swir>2000)?1:0', gdalformat, rsgislib.TYPE_8UINT, bandDefns)
imagecalc.bandMath(outName, '(sel>60)&&(sel<94)&&(hand>5)?1:0', gdalformat,
                   rsgislib.TYPE_8UINT, bandDefns)
'''
file_read=gdal.Open(inFile)
mask=np.array(file_read.GetRasterBand(1).ReadAsArray())



# condition to select perm water pixels with low backscatter
print("Conditions to extract mask....")
mask[np.where(mask>3)] = 999
mask[np.where(mask<3)] = 0
mask[np.where(mask==999)] = 1

# write new dataset
# create new file
print("Writing raster result....")
예제 #18
0
cmd='gdal_calc.py -A %s --A_band=2 --outfile=%s --calc="nan_to_num(A)"' %(inputImage,b2)
os.system(cmd)
cmd='gdal_calc.py -A %s --A_band=3 --outfile=%s --calc="nan_to_num(A)"' %(inputImage,b3)
os.system(cmd)


gdalformat = 'KEA'

# define the output names
b1_nan=b1.replace('.tif','_b1_nan.tif')
b2_nan=b2.replace('.tif','_b2_nan.tif')
b3_nan=b3.replace('.tif','_b3_nan.tif')

bandDefns = []
bandDefns.append(BandDefn('b1', b1, 1))
imagecalc.bandMath(b1_nan, '(b1==0.0)?-999:b1', gdalformat, rsgislib.TYPE_32FLOAT, bandDefns)
bandDefns = []
bandDefns.append(BandDefn('b2', b2, 1))
imagecalc.bandMath(b2_nan, '(b2==0.0)?-999:b2', gdalformat, rsgislib.TYPE_32FLOAT, bandDefns)
bandDefns = []
bandDefns.append(BandDefn('b3', b3, 1))
imagecalc.bandMath(b3_nan, '(b3==0.0)?-999:b3', gdalformat, rsgislib.TYPE_32FLOAT, bandDefns)

gdalformat='GTiff'
gdaltype = rsgislib.TYPE_32FLOAT
imageutils.stackImageBands([b1_nan,b2_nan,b3_nan], ['VV','VH','VVdivVH']  , nanOut, None, -999, gdalformat, gdaltype)

try:
	os.remove(b1)
	os.remove(b2)
	os.remove(b3)
def create_palsar_rgb_composite(in_tile_dir, stretchtxt, calcCoVHH, calcCoVHV):
    """
    Create scaled 8-bit RGB composite
    of HH, HV and HH/HV PALSAR data in GeoTiff format

    Stores intermediate files in temp directory and removes
    after.

    """
    try:
        in_hh_file = glob.glob(os.path.join(in_tile_dir, HH_FILE_PATTERN))[0]
        in_hv_file = glob.glob(os.path.join(in_tile_dir, HV_FILE_PATTERN))[0]
    except IndexError:
        raise Exception('Could not find data - check filenames')

    tile_basename = os.path.basename(in_tile_dir)
    out_composite = os.path.join(in_tile_dir, tile_basename + '_composite.tif')

    # Make temp directory for intermediate files
    temp_dir = tempfile.mkdtemp(prefix='palsar_stack_')
    #print("Temp DIR: " + temp_dir)

    # Create HH/HV image
    temp_3rdBand_file = ''
    bandName = ''
    if calcCoVHH:
        temp_3rdBand_file = os.path.join(temp_dir,
                                         tile_basename + '_covhh.tif')
        imagefilter.applyCoeffOfVarFilter(in_hh_file, temp_3rdBand_file, 5,
                                          'GTiff', rsgislib.TYPE_32FLOAT)
        bandName = 'CoVHH'
    elif calcCoVHV:
        temp_3rdBand_file = os.path.join(temp_dir,
                                         tile_basename + '_covhv.tif')
        imagefilter.applyCoeffOfVarFilter(in_hv_file, temp_3rdBand_file, 5,
                                          'GTiff', rsgislib.TYPE_32FLOAT)
        bandName = 'CoVHV'
    else:
        temp_3rdBand_file = os.path.join(temp_dir, tile_basename + '_hhhv.tif')
        bandDefns = [
            imagecalc.BandDefn('hh', in_hh_file, 1),
            imagecalc.BandDefn('hv', in_hv_file, 1)
        ]
        imagecalc.bandMath(temp_3rdBand_file, 'hh/hv', 'GTiff',
                           rsgislib.TYPE_32FLOAT, bandDefns)
        bandName = 'HH/HV'

    # Create stack
    temp_stack = os.path.join(temp_dir, tile_basename + '_stack.tif')
    bands_list = [in_hh_file, in_hv_file, temp_3rdBand_file]
    band_names = ['HH', 'HV', bandName]
    imageutils.stackImageBands(bands_list, band_names, temp_stack, None, 0,
                               'GTiff', rsgislib.TYPE_32FLOAT)

    # Apply stretch
    if stretchtxt == None:
        imageutils.stretchImage(temp_stack, out_composite, False, '', True,
                                False, 'GTiff', rsgislib.TYPE_8INT,
                                imageutils.STRETCH_LINEARSTDDEV, STRETCH_STDEV)
    else:
        imageutils.stretchImageWithStats(temp_stack, out_composite, stretchtxt,
                                         'GTiff', rsgislib.TYPE_8INT,
                                         imageutils.STRETCH_LINEARMINMAX, 0)

    # Remove temp directory
    shutil.rmtree(temp_dir)