本文整理匯總了Python中gdal.UseExceptions方法的典型用法代碼示例。如果您正苦於以下問題:Python gdal.UseExceptions方法的具體用法?Python gdal.UseExceptions怎麽用?Python gdal.UseExceptions使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類gdal
的用法示例。
在下文中一共展示了gdal.UseExceptions方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: singleBand
# 需要導入模塊: import gdal [as 別名]
# 或者: from gdal import UseExceptions [as 別名]
def singleBand(self, rasterFp):
gdal.UseExceptions()
'''打開柵格數據'''
try:
src_ds=gdal.Open(rasterFp)
except RuntimeError as e:
print( 'Unable to open %s'% rasterFp)
sys.exit(1)
#獲取柵格信息
rasterInfo={"RasterXSize":src_ds.RasterXSize,
"RasterYSize":src_ds.RasterYSize,
"RasterProjection":src_ds.GetProjection(),
"GeoTransform":src_ds.GetGeoTransform()}
'''獲取單波段像元值'''
bandValue=src_ds.GetRasterBand(1).ReadAsArray().astype(np.float)
print("readed rasterDate!")
return bandValue,rasterInfo #返回該波段,為數組形式
#影像數據裁切
示例2: singleBand
# 需要導入模塊: import gdal [as 別名]
# 或者: from gdal import UseExceptions [as 別名]
def singleBand(self, rasterFp):
gdal.UseExceptions()
'''打開柵格數據'''
try:
src_ds=gdal.Open(rasterFp)
except RuntimeError as e:
print( 'Unable to open %s'% rasterFp)
sys.exit(1)
#獲取柵格信息
rasterInfo={"RasterXSize":src_ds.RasterXSize,
"RasterYSize":src_ds.RasterYSize,
"RasterProjection":src_ds.GetProjection(),
"GeoTransform":src_ds.GetGeoTransform()}
'''獲取單波段像元值'''
bandValue=src_ds.GetRasterBand(1).ReadAsArray().astype(np.float)
print("readed rasterDate!")
return bandValue,rasterInfo #返回該波段,為數組形式
示例3: singleBand
# 需要導入模塊: import gdal [as 別名]
# 或者: from gdal import UseExceptions [as 別名]
def singleBand(rasterFp):
gdal.UseExceptions()
'''打開柵格數據'''
try:
src_ds=gdal.Open(rasterFp)
except RuntimeError as e:
# print( 'Unable to open %s'% rasterFp)
sys.exit(1)
#獲取柵格信息
rasterInfo={"RasterXSize":src_ds.RasterXSize,
"RasterYSize":src_ds.RasterYSize,
"RasterProjection":src_ds.GetProjection(),
"GeoTransform":src_ds.GetGeoTransform()}
'''獲取單波段像元值'''
bandValue=src_ds.GetRasterBand(1).ReadAsArray().astype(np.float)
# print("readed rasterDate!")
return bandValue,rasterInfo #返回該波段,為數組形式
示例4: rasterRW
# 需要導入模塊: import gdal [as 別名]
# 或者: from gdal import UseExceptions [as 別名]
def rasterRW(self, LSTValue,resultsPath,LSTSavingFn,para):
gdal.UseExceptions()
# '''打開柵格數據'''
# try:
# src_ds=gdal.Open(os.path.join(resultsPath,LSTSavingFn))
# except RuntimeError as e:
# print( 'Unable to open %s'% os.path.join(resultsPath,LSTSavingFn))
# print(e)
# sys.exit(1)
# print("metadata:",src_ds.GetMetadata())
'''初始化輸出柵格'''
driver=gdal.GetDriverByName('GTiff')
print(para['RasterXSize'],para['RasterYSize'])
out_raster=driver.Create(os.path.join(resultsPath,LSTSavingFn),para['RasterXSize'],para['RasterYSize'],1,gdal.GDT_Float64)
out_raster.SetProjection(para['RasterProjection']) #設置投影與參考柵格同
out_raster.SetGeoTransform(para['GeoTransform']) #配置地理轉換與參考柵格同
'''將數組傳給柵格波段,為柵格值'''
out_band=out_raster.GetRasterBand(1)
out_band.WriteArray(LSTValue)
# '''設置overview'''
# overviews = pb.compute_overview_levels(out_raster.GetRasterBand(1))
# out_raster.BuildOverviews('average', overviews)
'''清理緩存與移除數據源'''
out_band.FlushCache()
out_band.ComputeStatistics(False)
# del src_ds,out_raster,out_band
del out_raster,out_band
##解譯精度評價。采樣的數據是使用GIS平台人工判斷提取,樣例文件在Github中獲取。
示例5: singleRaster
# 需要導入模塊: import gdal [as 別名]
# 或者: from gdal import UseExceptions [as 別名]
def singleRaster(fn,raster_lyr):
gdal.UseExceptions()
'''打開柵格數據'''
try:
src_ds=gdal.Open(os.path.join(fn,raster_lyr))
except RuntimeError as e:
print( 'Unable to open %s'% os.path.join(fn,raster_lyr))
sys.exit(1)
print("metadata:",src_ds.GetMetadata())
'''獲取所有波段'''
band=src_ds.GetRasterBand(1).ReadAsArray().astype(np.float)
return band #返回該波段,為數組形式
示例6: loadModelPredict
# 需要導入模塊: import gdal [as 別名]
# 或者: from gdal import UseExceptions [as 別名]
def loadModelPredict(studyRegionFn,modelPath,mask):
gdal.UseExceptions()
'''打開柵格數據'''
try:
src_ds=gdal.Open(studyRegionFn)
except RuntimeError as e:
print( 'Unable to open %s'% studyRegionFn)
# print(e)
sys.exit(1)
print("metadata:",src_ds.GetMetadata())
'''獲取波段'''
studyRegion=src_ds.GetRasterBand(1).ReadAsArray().astype(np.float)
'''按照mask劃分解釋變量和目標變量'''
image_shape=(row, col)
dataFlatten=np.copy(studyRegion).reshape(-1)
maskFlatten=mask.reshape(-1)
maskBool=maskFlatten==1
X=dataFlatten[maskBool].reshape(1,-1)
model=joblib.load(modelPath) #加載已經訓練好的回歸模型,用於預測
y_p=model.predict(X)
print(X.std(),y_p.std(),X.max(),y_p.max())
y_p_scaled=(y_p - y_p.min()) / (y_p.max() - y_p.min()) * (X.max() - X.min()) + X.min() #調整預測數據的區間與解釋變量的區間同,也可忽略
print(dataFlatten.shape,maskBool.shape,y_p_scaled.shape)
true_pred=dataFlatten
true_pred[maskBool==False]=y_p_scaled.reshape(-1) #拚合解釋變量和預測數據
'''打印顯示結果'''
fig, (ax1, ax2) = plt.subplots(figsize=(17, 17), ncols=2)
pre=ax1.imshow(studyRegion, cmap=plt.cm.RdYlGn, interpolation='none')
# fig.colorbar(pre, ax=ax1)
ori=ax2.imshow(true_pred.reshape(image_shape), cmap=plt.cm.RdYlGn, interpolation='none')
# fig.colorbar(ori, ax=ax2)
plt.show()
return true_pred.reshape(image_shape)
示例7: rasterRW
# 需要導入模塊: import gdal [as 別名]
# 或者: from gdal import UseExceptions [as 別名]
def rasterRW(self, rasterValue,resultsPath,rasterSavingFn,para):
gdal.UseExceptions()
# '''打開柵格數據'''
# try:
# src_ds=gdal.Open(os.path.join(resultsPath,rasterSavingFn))
# except RuntimeError as e:
# print( 'Unable to open %s'% os.path.join(resultsPath,rasterSavingFn))
# print(e)
# sys.exit(1)
# print("metadata:",src_ds.GetMetadata())
'''初始化輸出柵格'''
driver=gdal.GetDriverByName('GTiff')
print(para['RasterXSize'],para['RasterYSize'])
out_raster=driver.Create(os.path.join(resultsPath,rasterSavingFn),para['RasterXSize'],para['RasterYSize'],1,gdal.GDT_Float64)
out_raster.SetProjection(para['RasterProjection']) #設置投影與參考柵格同
out_raster.SetGeoTransform(para['GeoTransform']) #配置地理轉換與參考柵格同
'''將數組傳給柵格波段,為柵格值'''
out_band=out_raster.GetRasterBand(1)
out_band.WriteArray(rasterValue)
# '''設置overview'''
# overviews = pb.compute_overview_levels(out_raster.GetRasterBand(1))
# out_raster.BuildOverviews('average', overviews)
'''清理緩存與移除數據源'''
out_band.FlushCache()
out_band.ComputeStatistics(False)
# del src_ds,out_raster,out_band
del out_raster,out_band
示例8: rasterRW
# 需要導入模塊: import gdal [as 別名]
# 或者: from gdal import UseExceptions [as 別名]
def rasterRW(rasterValue,resultsPath,rasterSavingFn,para):
gdal.UseExceptions()
# '''打開柵格數據'''
# try:
# src_ds=gdal.Open(os.path.join(resultsPath,rasterSavingFn))
# except RuntimeError as e:
# print( 'Unable to open %s'% os.path.join(resultsPath,rasterSavingFn))
# print(e)
# sys.exit(1)
# print("metadata:",src_ds.GetMetadata())
'''初始化輸出柵格'''
driver=gdal.GetDriverByName('GTiff')
# print(para['RasterXSize'],para['RasterYSize'])
out_raster=driver.Create(os.path.join(resultsPath,rasterSavingFn),para['RasterXSize'],para['RasterYSize'],1,gdal.GDT_Float64)
out_raster.SetProjection(para['RasterProjection']) #設置投影與參考柵格同
out_raster.SetGeoTransform(para['GeoTransform']) #配置地理轉換與參考柵格同
'''將數組傳給柵格波段,為柵格值'''
out_band=out_raster.GetRasterBand(1)
out_band.WriteArray(rasterValue)
# '''設置overview'''
# overviews = pb.compute_overview_levels(out_raster.GetRasterBand(1))
# out_raster.BuildOverviews('average', overviews)
'''清理緩存與移除數據源'''
out_band.FlushCache()
out_band.ComputeStatistics(False)
# del src_ds,out_raster,out_band
del out_raster,out_band
示例9: rasterRW
# 需要導入模塊: import gdal [as 別名]
# 或者: from gdal import UseExceptions [as 別名]
def rasterRW(self, rasterArray,resultsPath,resultsFn,para):
gdal.UseExceptions()
# '''打開柵格數據'''
# try:
# src_ds=gdal.Open(os.path.join(resultsPath,resultsFn))
# except RuntimeError as e:
# print( 'Unable to open %s'% os.path.join(resultsPath,resultsFn))
# print(e)
# sys.exit(1)
# print("metadata:",src_ds.GetMetadata())
'''初始化輸出柵格'''
driver=gdal.GetDriverByName('GTiff')
print(para['RasterXSize'],para['RasterYSize'])
out_raster=driver.Create(os.path.join(resultsPath,resultsFn),para['RasterXSize'],para['RasterYSize'],1,gdal.GDT_Float64)
out_raster.SetProjection(para['RasterProjection']) #設置投影與參考柵格同
out_raster.SetGeoTransform(para['GeoTransform']) #配置地理轉換與參考柵格同
'''將數組傳給柵格波段,為柵格值'''
out_band=out_raster.GetRasterBand(1)
out_band.WriteArray(rasterArray)
# '''設置overview'''
# overviews = pb.compute_overview_levels(out_raster.GetRasterBand(1))
# out_raster.BuildOverviews('average', overviews)
'''清理緩存與移除數據源'''
out_band.FlushCache()
out_band.ComputeStatistics(False)
# del src_ds,out_raster,out_band
print("raster saved successfully!")
del out_raster,out_band
示例10: export_geomap2geotiff
# 需要導入模塊: import gdal [as 別名]
# 或者: from gdal import UseExceptions [as 別名]
def export_geomap2geotiff(path, geo_model, geo_map=None, geotiff_filepath=None):
"""
Args:
path (str): Filepath for the exported geotiff, must end in .tif
geo_map (np.ndarray): 2-D array containing the geological map
cmap (matplotlib colormap): The colormap to be used for the export
geotiff_filepath (str): Filepath of the template geotiff
Returns:
Saves the geological map as a geotiff to the given path.
"""
import gdal
plot = PlotData2D(geo_model)
cmap = plot._cmap
norm = plot._norm
if geo_map is None:
geo_map = geo_model.solutions.geological_map[0].reshape(geo_model._grid.topography.resolution)
if geotiff_filepath is None:
# call the other function
print('stupid')
# **********************************************************************
geo_map_rgb = SM(norm=norm, cmap=cmap).to_rgba(geo_map.T) # r,g,b,alpha
# **********************************************************************
# gdal.UseExceptions()
ds = gdal.Open(geotiff_filepath)
band = ds.GetRasterBand(1)
arr = band.ReadAsArray()
[cols, rows] = arr.shape
outFileName = path
driver = gdal.GetDriverByName("GTiff")
options = ['PROFILE=GeoTiff', 'PHOTOMETRIC=RGB', 'COMPRESS=JPEG']
outdata = driver.Create(outFileName, rows, cols, 3, gdal.GDT_Byte, options=options)
outdata.SetGeoTransform(ds.GetGeoTransform()) # sets same geotransform as input
outdata.SetProjection(ds.GetProjection()) # sets same projection as input
outdata.GetRasterBand(1).WriteArray(geo_map_rgb[:, ::-1, 0].T * 256)
outdata.GetRasterBand(2).WriteArray(geo_map_rgb[:, ::-1, 1].T * 256)
outdata.GetRasterBand(3).WriteArray(geo_map_rgb[:, ::-1, 2].T * 256)
outdata.GetRasterBand(1).SetColorInterpretation(gdal.GCI_RedBand)
outdata.GetRasterBand(2).SetColorInterpretation(gdal.GCI_GreenBand)
outdata.GetRasterBand(3).SetColorInterpretation(gdal.GCI_BlueBand)
# outdata.GetRasterBand(4).SetColorInterpretation(gdal.GCI_AlphaBand) # alpha band
# outdata.GetRasterBand(1).SetNoDataValue(999)##if you want these values transparent
outdata.FlushCache() # saves to disk
outdata = None # closes file (important)
band = None
ds = None
print("Successfully exported geological map to " +path)
示例11: rasterCal
# 需要導入模塊: import gdal [as 別名]
# 或者: from gdal import UseExceptions [as 別名]
def rasterCal(fn,raster_lyr,raster_lyr_w):
gdal.UseExceptions()
'''打開柵格數據'''
try:
src_ds=gdal.Open(os.path.join(fn,raster_lyr))
except RuntimeError as e:
print( 'Unable to open %s'% os.path.join(fn,raster_lyr))
print(e)
sys.exit(1)
print("metadata:",src_ds.GetMetadata())
'''獲取所有波段'''
srcband=[]
for band_num in range(1,8):
try:
srcband.append(src_ds.GetRasterBand(band_num))
except RuntimeError as e:
print('Band ( %i ) not found' % band_num)
print(e)
sys.exit(1)
print(srcband)
'''獲取用於NDVI計算的紅和近紅波段數組,並計算ndvi'''
red=srcband[3].ReadAsArray().astype(np.float)
nir=srcband[4].ReadAsArray()
red=np.ma.masked_where(nir+red==0,red) #確定分母不為零
ndvi=(nir-red)/(nir+red)
ndvi=ndvi.filled(-99)
print(ndvi.shape,ndvi.std(),ndvi.max(),ndvi.min(),ndvi.mean())
'''初始化輸出柵格'''
driver=gdal.GetDriverByName('GTiff')
if os.path.exists(os.path.join(fn,raster_lyr_w)):
driver.Delete(os.path.join(fn,raster_lyr_w))
out_raster=driver.Create(os.path.join(fn,raster_lyr_w),src_ds.RasterXSize,src_ds.RasterYSize,1,gdal.GDT_Float64)
out_raster.SetProjection(src_ds.GetProjection()) #設置投影與參考柵格同
out_raster.SetGeoTransform(src_ds.GetGeoTransform()) #配置地理轉換與參考柵格同
'''將數組傳給柵格波段,為柵格值'''
out_band=out_raster.GetRasterBand(1)
out_band.WriteArray(ndvi)
'''設置overview'''
overviews = pb.compute_overview_levels(out_raster.GetRasterBand(1))
out_raster.BuildOverviews('average', overviews)
'''清理緩存與移除數據源'''
out_band.FlushCache()
out_band.ComputeStatistics(False)
del src_ds,out_raster,out_band
return ndvi
示例12: rasterRW
# 需要導入模塊: import gdal [as 別名]
# 或者: from gdal import UseExceptions [as 別名]
def rasterRW(fn,raster_lyr,raster_lyr_w):
gdal.UseExceptions()
'''打開柵格數據'''
try:
src_ds=gdal.Open(os.path.join(fn,raster_lyr))
except RuntimeError as e:
print( 'Unable to open %s'% os.path.join(fn,raster_lyr))
print(e)
sys.exit(1)
print("metadata:",src_ds.GetMetadata())
'''獲取所有波段'''
srcband=[]
for band_num in range(1,5):
try:
srcband.append(src_ds.GetRasterBand(band_num))
except RuntimeError as e:
print('Band ( %i ) not found' % band_num)
print(e)
sys.exit(1)
print(srcband)
'''獲取用於NDVI計算的紅和近紅波段數組,並計算ndvi'''
red=srcband[0].ReadAsArray().astype(np.float)
nir=srcband[3].ReadAsArray()
red=np.ma.masked_where(nir+red==0,red)
ndvi=(nir-red)/(nir+red)
ndvi=ndvi.filled(-99)
print(ndvi.shape,ndvi.std())
'''初始化輸出柵格'''
driver=gdal.GetDriverByName('GTiff')
out_raster=driver.Create(os.path.join(fn,raster_lyr_w),src_ds.RasterXSize,src_ds.RasterYSize,1,gdal.GDT_Float64)
out_raster.SetProjection(src_ds.GetProjection()) #設置投影與參考柵格同
out_raster.SetGeoTransform(src_ds.GetGeoTransform()) #配置地理轉換與參考柵格同
'''將數組傳給柵格波段,為柵格值'''
out_band=out_raster.GetRasterBand(1)
out_band.WriteArray(ndvi)
'''設置overview'''
overviews = pb.compute_overview_levels(out_raster.GetRasterBand(1))
out_raster.BuildOverviews('average', overviews)
'''清理緩存與移除數據源'''
out_band.FlushCache()
out_band.ComputeStatistics(False)
del src_ds,out_raster,out_band