GDAL notes --chapter9

1. The band synthesis independent of a raster image

# Independent raster image a band synthesis 
Import OS
 Import numpy AS NP
 from OSGeo Import GDAL 

the os.chdir (R & lt ' E: \ Desktop file path \ GDAL \ osgeopy-Data \ osgeopy-Data \ Washington ' ) 
band1_fn = R & lt ' E: \ Desktop file path \ gdal \ osgeopy-data \ osgeopy -data \ the Landsat \ Washington \ p047r027_7t20000730_z10_nn10.tif ' 
band2_fn = R & lt ' E: \ Desktop file path \ gdal \ osgeopy-data \ osgeopy -data \ the Landsat \ Washington \ p047r027_7t20000730_z10_nn20.tif ' 
band3_fn = R & lt ' E: \ Desktop file path \ GDAL \ osgeopy-Data \ osgeopy-Data \ the Landsat \ Washington \ p047r027_7t20000730_z10_nn30.tif '

in_ds = gdal.Open(band1_fn)
in_band = in_ds.GetRasterBand(1)
gtiff_driver = gdal.GetDriverByName('GTiff')
out_ds = gtiff_driver.Create('nat_color.tif', in_band.XSize, in_band.YSize, 3, in_band.DataType)
out_ds.SetProjection(in_ds.GetProjection())
print(in_ds.GetGeoTransform())
out_ds.SetGeoTransform(in_ds.GetGeoTransform())

in_data = in_band.ReadAsArray()
out_band = out_ds.GetRasterBand(3)
out_band.WriteArray(in_data)

in_ds =gdal.Open (band2_fn) 
out_band = out_ds.GetRasterBand (2 ) 
out_band.WriteArray ( in_ds.ReadAsArray () )
 # in data set call ReadAsArray, if the data set has a plurality of bands, then to obtain a three-dimensional array 
# if the data set is a single-band, two-dimensional array is returned. The role of GetRasterBand just returned to query the band 

in_ds = gdal.Open (band3_fn) 
out_band = out_ds.GetRasterBand (1 ) 
out_band.WriteArray (in_ds.ReadAsArray ()) out_ds.FlushCache ()


 # to ensure that data is written to disk, refresh the cache 
for I in Range (. 1,. 4 ): 
    out_ds.GetRasterBand (I) .ComputeStatistics (False) 
# statistics are calculated for each band 
out_ds.BuildOverviews ( ' Average' , [2,4,8,16,32 ])
 # Create overview view 
del out_ds
 # release dataset

2.band.ReadAsArray(xoff,yoff,win_xsize,win_ysize,buf_xsize,buf_ysize,buf_obj)

# XOFF column is the starting point, win_xsize number of columns is read, buf_xsize number of columns of the array output, and if the former is different resampling will, buf_obj storage array type 
# Data type conversion 
data = np.empty ((3, 6 ), = DTYPE a float) 
band.ReadAsArrray ( 14000,6000,6,3, buf_obj = Data) 

Data = band.ReadAsArrray (1400,600,6,3) .astype (a float)

 

3. The raster processing block

import os
import numpy as np
from osgeo import gdal

os.chdir(r'E:\桌面文件保存路径\gdal\osgeopy-data\osgeopy-data\Landsat\Washington')

in_ds = gdal.Open('')
in_band = in_ds.GetRasterBand(1)
xsize = in_band.XSize
ysize = in_band.YSize

block_xsize, block_ysize = in_band.GetBlockSize()
nodata = in_band.GetNoDataValue()  #获取nodata

out_ds = in_ds.GetDriver().Create('dem_feet.tif', xsize, ysize, 1, in_band.DataType)
out_ds.SetProjection(in_ds.GetProjection())
out_ds.SetGeoTransform(in_ds.GetGeoTransform())
out_band = out_ds.GetRasterBand(1)

for x in range(0, xsize, block_xsize):
    if x+block_xsize < xsize:
        cols = block_xsize
    else:
        cols = xsize-x
    for y in range(0, ysize, block_ysize):
        if y+block_ysize < ysize:
            rows = block_ysize
        else:
            rows = ysize-y
        data = in_band.ReadAsArray(x, y, cols, rows)
        data = np.where(data == nodata, nodata, data*3.28084)
        out_band.WriteArray(data, x, y)

out_band.FlushCache()
out_band.SetNoDataValue(nodata)  #将nodata排除在外
out_band.ComputeStatistics(False)
out_ds.BuildOverviews('average', [2, 4, 8, 16, 32])
del out_ds

4.GeoTransform

# Using real-world coordinates 
# geotransform 
# origin 0,3 x \ y coordinate of coordinate reality, generally projected coordinate 
# 1,5-pixel width and height (the height of a negative value) 
# 2,4 x \ y rotation 
gt = ds. GetGeoTransform ()   # forward transform coordinates from image coordinates to real 
inv_gt = gdal.InvGeoTransform (gt)   # inverse transform 

Qoffsets = gdal.ApplyGeoTransfrom (inv_gt, 465 200, 5.296 million )
 #ApplyGeoTransform returns float Switch needs to be passed to ReadAsArray integer 
XOFF, Yoff = map (int, Qoffsets)   # Python built-in map function for mapping the data do 
value = band.ReadAsArrray (XOFF, Yoff,. 1,. 1 ) [0, 0] 

data = band.ReadAsArray () 
XOFF, Yoff Map = (int, gdal.ApplyGeoTransform (inv_gt, 465.2 thousand, 5.296 million ))
valueData = [Yoff, XOFF]   # numpy array [row, column], and different gdal

5. subset of the saved image

# Extracting and storing the image subset 
Import OS
 from OSGeo Import GDAL 

vashon_ulx, vashon_uly = 532 000, 5.2626 million 
vashon_lrx, vashon_lry = 548.5 thousand, 5.2415 million 

the os.chdir (R & lt ' E: \ Desktop file path \ gdal \ osgeopy-data \ osgeopy- Data \ the Landsat \ Washington ' ) 
in_ds = gdal.Open ( ' nat_color.tif ' ) 
in_gt = in_ds.GetGeoTransform () 

inv_gt = gdal.InvGeoTransform (in_gt)
 IF gdal.VersionInfo () [0] == ' . 1 ' :
     IF inv_gt [0] ==. 1 :
        inv_gt = inv_gt[1]
    else:
        raise RuntimeError('Inverse geotransform failed')
elif inv_gt is None:
    raise RuntimeError('Inverse geotransform failed')

offsets_ul = gdal.ApplyGeoTransform(inv_gt, vashon_ulx, vashon_uly)
offsets_lr = gdal.ApplyGeoTransform(inv_gt, vashon_lrx, vashon_lry)
off_ulx, off_uly = map(int, offsets_ul)   #取整得到行列值
off_lrx, off_lry = map(int, offsets_lr)

rows Off_lry = - off_uly 
Columns = off_lrx - off_ulx 

gtiff_driver = gdal.GetDriverByName ( ' GTiff ' ) 
out_ds = gtiff_driver.Create ( ' vashon2.tif ' , Columns, rows,. 3 ) 
out_ds.SetProjection (in_ds.GetProjection ()) subset_ulx, subset_uly
 gdal.ApplyGeoTransform = (in_gt, off_ulx, off_uly)   # herein as forward conversion is to prevent the original fall somewhere in the middle left corner pixel 
Print (subset_ulx)   # calculated 531995.25 \ 5262624.75 original left corner, is transformed intermediate pixel does not fall. 
Print (subset_uly) 
out_gt = List (in_gt)   #元组转列表,可修改
out_gt[0] = subset_ulx
out_gt[3] = subset_uly
out_ds.SetGeoTransform(out_gt)

for i in range(1, 4):
    in_band = in_ds.GetRasterBand(i)
    out_band = out_ds.GetRasterBand(i)
    data = in_band.ReadAsArray(off_ulx, off_uly, columns, rows)
    out_band.WriteArray(data)

out_ds.FlushCache()
del out_ds

6. The image resampling

import os
import numpy as np
from osgeo import gdal

os.chdir(r'')
in_ds = gdal.Open(r'')
in_band = in_ds.GetRasterBand(1)
out_rows = in_band.YSize*2
out_columns = in_band.XSize*2

gtiff_driver = gdal.GetDriverByName('GTiff')
out_ds = gtiff_driver.Create('band_resampled.tif', out_columns, out_rows)

out_ds.SetProjection(in_ds.GetProjection())
geotransform = list(in_ds.GetGeoTransform())
geotransform[1] /= 2
geotransform[5] /= 2
out_ds.SetGeoTransform(geotransform)

data = in_band.ReadAsArray(buf_xsize=out_columns, buf_ysize=out_rows)
out_band = out_ds.GetRasterBand(1)
out_band.WriteArray(data)

out_band.FlushCache()
out_band.ComputeStatistics(False)
out_ds.BuildOverviews('average', [2, 4, 8, 16, 32, 64])
del out_ds

#重采样为更大的元素
data = np.empty((2, 3), np.int)  #2行3列
band.ReadAsArray(1400, 6000, 6, 4, buf_obj=data)

 7. The readRaster \ WriteRaster read stored as a sequence of bytes

 

# ReadRaster \ WriteRaster stored as a sequence of bytes read 
ds.ReadRaster (1400, 6000, 2, 2, band_list = [. 1 ]) 
ds.WriteRaster ( 1400, 6000,. 6,. 4, Data, band_list = [. 1 ]) 

# byte sequence readRaster 
Import OS
 Import numpy AS NP
 from OSGeo Import GDAL 

in_ds = gdal.Open (R & lt ' nat_color.tif ' )
 out_rows  = int (in_ds.RasterYSize / 2)  # DS read directly the number of ranks 
out_columns = int (in_ds. RasterXSize / 2 )
 num_bands = in_ds.RasterCount   # DS read band number 

gtiff_driver = gdal.GetDriverByName (' GTiff ' ) 
out_ds = gtiff_driver.Create ( ' nat_color_resampled.tif ' , out_columns, out_rows, num_bands) 

out_ds.SetProjection (in_ds.GetProjection ()) 
geotransform = List (in_ds.GetGeoTransform ()) 
geotransform [ . 1] = 2 * 
geotransform [ . 5] = 2 * 
out_ds.SetGeoTransform (geotransform) 

data = in_ds.ReadRaster (buf_xsize = out_columns, buf_ysize = out_rows)
 # using a smaller buffer to read and write data, resampling 
out_ds.WriteRaster (0, 0, out_columns, out_rows , data)
 # write data as the output data source 
out_ds.FlushCache ()
 for I in range(num_bands):
    out_ds.GetRasterBand(i+1).ComputeStatistics(False)
out_ds.BuildOverviews('average', [2, 4, 8, 16])
del out_ds

8. The sub-data sets HDF (modis)

 

# Subdatasets HDF, GDAL version needs to support HDF 
from OSGeo Import GDAL 

ds = gdal.Open (r ' E: \ Desktop file path \ gdal \ osgeopy-data \ osgeopy -data \ Modis \ MYD13Q1.A2014313.h20v11 .005.2014330092746.hdf ' ) 
subdatasets = ds.GetSubDatasets ()   # returns the list of sub data sets 
Print ( ' Number The subdatasets of:. {} the format (len (subdatasets)) ' )
 for SD in subdatasets:
     Print ( ' the Name: {0 } \ nDescription: {}. 1 \ n- ' .format (* SD)) 
ndvi_ds = gdal.Open (subdatasets [0] [0])   # Of a [0] is read first set of data, the second data set name of the current is read

 

9.xml save images (driver.CreateCopy)

ds = gdal.Open('listing9—6.xml')
gdal.GetDriverByName('PNG').CreateCopy('liberty.png', ds)
#driver.CreateCopy('', ds)用来复制ds

 

Guess you like

Origin www.cnblogs.com/ljwgis/p/12595981.html