使用Python进行nc转tif的3种情况解决
本文将提供使用Python对nc文件进行tif格式转换的方法,分为以下3种情况:
- 转换单个nc文件
- 批量转换nc文件夹下所有文件
- 批量转换nc多级子文件夹下所有文件
在进行操作之前,请确保您的Python环境配置正确,并且已经安装了相关的库。
1.转换单个nc文件
这是最简单的情况,只需要用Python编写一个脚本来实现即可。代码如下:
from netCDF4 import Dataset
from osgeo import gdal
def nc2tif(nc_file, tif_file):
dataset = Dataset(nc_file)
var = dataset.variables[‘var_name’] # var_name是您要转换的变量名
x = dataset.variables[‘longitude’][:]
y = dataset.variables[‘latitude’][:]
data = var[:]
# 将地理经纬度转为投影坐标
projection = gdal.osr.SpatialReference()
projection.SetWellKnownGeogCS("WGS84")
projection.SetUTM(30, True)
projection.SetFalseEasting(500000)
projection.SetFalseNorthing(10000000)
projection.SetCentralMeridian(113)
projection.SetScaleFactor(0.9996)
# 定义栅格数据
driver = gdal.GetDriverByName('GTiff')
dst_ds = driver.Create(tif_file, len(x), len(y), 1, gdal.GDT_Float32)
dst_ds.SetProjection(projection.ExportToWkt())
dst_ds.SetGeoTransform((x[0], (x[1]-x[0]), 0, y[0], 0, (y[0]-y[1])))
# 将数据写入栅格
dst_ds.GetRasterBand(1).WriteArray(data)
dst_ds = None
print(nc_file, 'to', tif_file, 'success!')
if __name__ == '__main__':
nc_file = 'path/to/nc_file'
tif_file = 'path/to/tif_file'
nc2tif(nc_file, tif_file)
2.批量转换nc文件夹下所有文件
有了第一步的实践,我们现在可以轻松地处理许多的nc文件,这里我们需要编写一个循环来完成。代码如下:
import os
from netCDF4 import Dataset
from osgeo import gdal
def nc2tif(nc_file, tif_file):
dataset = Dataset(nc_file, 'r')
var = dataset.variables[‘var_name’] # var_name是您要转换的变量名。
x = dataset.variables[‘longitude’][:]
y = dataset.variables[‘latitude’][:]
data = var[:]
# 将地理经纬度转为投影坐标
projection = gdal.osr.SpatialReference()
projection.SetWellKnownGeogCS("WGS84")
projection.SetUTM(30, True)
projection.SetFalseEasting(500000)
projection.SetFalseNorthing(10000000)
projection.SetCentralMeridian(113)
projection.SetScaleFactor(0.9996)
# 定义栅格数据
driver = gdal.GetDriverByName('GTiff')
dst_ds = driver.Create(tif_file, len(x), len(y), 1, gdal.GDT_Float32)
dst_ds.SetProjection(projection.ExportToWkt())
dst_ds.SetGeoTransform((x[0], (x[1]-x[0]), 0, y[0], 0, (y[0]-y[1])))
# 将数据写入栅格
dst_ds.GetRasterBand(1).WriteArray(data)
dst_ds = None
print(nc_file, 'to', tif_file, '成功!')
if __name__ == '__main__':
input_folder = 'path/to/nc/folder'
output_folder = 'path/to/tif/folder'
for filename in os.listdir(input_folder):
if filename.endswith('.nc'):
nc_file = os.path.join(input_folder, filename)
tif_file = os.path.join(output_folder, filename.replace('.nc', '.tif'))
nc2tif(nc_file, tif_file)
3.批量转换nc多级子文件夹下所有文件
针对这个情况,我们需要递归遍历每个子文件夹,并对其中的nc文件进行转换。代码如下:
import os
from netCDF4 import Dataset
from osgeo import gdal
def nc2tif(nc_file, tif_file):
dataset = Dataset(nc_file, 'r')
var = dataset.variables[‘var_name’] # var_name是您要转换的变量名。
x = dataset.variables[‘longitude’][:]
y = dataset.variables[‘latitude’][:]
data = var[:]
# 将地理经纬度转为投影坐标
projection = gdal.osr.SpatialReference()
projection.SetWellKnownGeogCS("WGS84")
projection.SetUTM(30, True)
projection.SetFalseEasting(500000)
projection.SetFalseNorthing(10000000)
projection.SetCentralMeridian(113)
projection.SetScaleFactor(0.9996)
# 定义栅格数据
driver = gdal.GetDriverByName('GTiff')
dst_ds = driver.Create(tif_file, len(x), len(y), 1, gdal.GDT_Float32)
dst_ds.SetProjection(projection.ExportToWkt())
dst_ds.SetGeoTransform((x[0], (x[1]-x[0]), 0, y[0], 0, (y[0]-y[1])))
# 将数据写入栅格
dst_ds.GetRasterBand(1).WriteArray(data)
dst_ds = None
print(nc_file, 'to', tif_file, 'success!')
def nc_folder2tif_folder(input_folder, output_folder):
for root, dirs, files in os.walk(input_folder):
for filename in files:
if filename.endswith('.nc'):
nc_file = os.path.join(root, filename)
tif_file = os.path.join(output_folder, os.path.relpath(nc_file, input_folder).replace('.nc', '.tif'))
os.makedirs(os.path.dirname(tif_file), exist_ok=True)
nc2tif(nc_file, tif_file)
if __name__ == '__main__':
input_folder = 'path/to/nc/folder'
output_folder = 'path/to/tif/folder'
nc_folder2tif_folder(input_folder, output_folder)
以上就是使用Python进行nc转tif的3种情况解决的完整攻略。下面给出两个使用示例。
示例一:使用第二种方法,将文件夹内所有的nc文件转换成tif
import os
from netCDF4 import Dataset
from osgeo import gdal
def nc2tif(nc_file, tif_file):
dataset = Dataset(nc_file, 'r')
var = dataset.variables[‘var_name’] # var_name是您要转换的变量名。
x = dataset.variables[‘longitude’][:]
y = dataset.variables[‘latitude’][:]
data = var[:]
# 将地理经纬度转为投影坐标
projection = gdal.osr.SpatialReference()
projection.SetWellKnownGeogCS("WGS84")
projection.SetUTM(30, True)
projection.SetFalseEasting(500000)
projection.SetFalseNorthing(10000000)
projection.SetCentralMeridian(113)
projection.SetScaleFactor(0.9996)
# 定义栅格数据
driver = gdal.GetDriverByName('GTiff')
dst_ds = driver.Create(tif_file, len(x), len(y), 1, gdal.GDT_Float32)
dst_ds.SetProjection(projection.ExportToWkt())
dst_ds.SetGeoTransform((x[0], (x[1]-x[0]), 0, y[0], 0, (y[0]-y[1])))
# 将数据写入栅格
dst_ds.GetRasterBand(1).WriteArray(data)
dst_ds = None
print(nc_file, 'to', tif_file, '成功!')
if __name__ == '__main__':
input_folder = 'path/to/nc/folder'
output_folder = 'path/to/tif/folder'
for filename in os.listdir(input_folder):
if filename.endswith('.nc'):
nc_file = os.path.join(input_folder, filename)
tif_file = os.path.join(output_folder, filename.replace('.nc', '.tif'))
nc2tif(nc_file, tif_file)
示例二:使用第三种方法,将多级子文件夹下的所有nc文件转换成tif
import os
from netCDF4 import Dataset
from osgeo import gdal
def nc2tif(nc_file, tif_file):
dataset = Dataset(nc_file, 'r')
var = dataset.variables[‘var_name’] # var_name是您要转换的变量名。
x = dataset.variables[‘longitude’][:]
y = dataset.variables[‘latitude’][:]
data = var[:]
# 将地理经纬度转为投影坐标
projection = gdal.osr.SpatialReference()
projection.SetWellKnownGeogCS("WGS84")
projection.SetUTM(30, True)
projection.SetFalseEasting(500000)
projection.SetFalseNorthing(10000000)
projection.SetCentralMeridian(113)
projection.SetScaleFactor(0.9996)
# 定义栅格数据
driver = gdal.GetDriverByName('GTiff')
dst_ds = driver.Create(tif_file, len(x), len(y), 1, gdal.GDT_Float32)
dst_ds.SetProjection(projection.ExportToWkt())
dst_ds.SetGeoTransform((x[0], (x[1]-x[0]), 0, y[0], 0, (y[0]-y[1])))
# 将数据写入栅格
dst_ds.GetRasterBand(1).WriteArray(data)
dst_ds = None
print(nc_file, 'to', tif_file, 'success!')
def nc_folder2tif_folder(input_folder, output_folder):
for root, dirs, files in os.walk(input_folder):
for filename in files:
if filename.endswith('.nc'):
nc_file = os.path.join(root, filename)
tif_file = os.path.join(output_folder, os.path.relpath(nc_file, input_folder).replace('.nc', '.tif'))
os.makedirs(os.path.dirname(tif_file), exist_ok=True)
nc2tif(nc_file, tif_file)
if __name__ == '__main__':
input_folder = 'path/to/nc/folder'
output_folder = 'path/to/tif/folder'
nc_folder2tif_folder(input_folder, output_folder)
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:使用python进行nc转tif的3种情况解决 - Python技术站