一、nc格式數據介紹
NetCDF全稱爲network Common Data Format,中文譯法爲“網絡通用數據格式”,netcdf文件開始的目的是用於存儲氣象科學中的數據,現在已經成爲許多數據採集軟件的生成文件的格式。從數學上來說,netcdf存儲的數據就是一個多自變量的單值函數。用公式來說就是f(x,y,z,…)=value, 函數的自變量x,y,z等在netcdf中叫做維(dimension)
或座標軸(axix),函數值value在netcdf中叫做變量(Variables).而自變量和函數值在物理學上的一些性質,比如計量單位(量綱)、物理學名稱等等在netcdf中就叫屬性(Attributes).
二、nc格式數據讀取
2.1 查看數據存儲內容
import netCDF4 as nc
file = ""
dataset =nc.Dataset(file)
print(dataset.variables.keys())
可以看到這個風場文件裏屬性有緯度、經度、時間、經向風、緯向風。
2.2 查看屬性值
import netCDF4 as nc
file = ""
dataset =nc.Dataset(file)
print(dataset.variables.keys())
#緯度
print(dataset.variables["latitude"][:])
#經度
print(dataset.variables["longitude"][:])
2.4 解析nc數據爲tiff的完整代碼
#!usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author :
@Email :
@Time : 2019/12/4 16:45
@File : weather.py
@Software: PyCharm
"""
import os
import gdal,osr
import netCDF4 as nc
def extract_nc(nc_file):
dataset = nc.Dataset(nc_file)
print(dataset.variables.keys())
lat = dataset.variables["latitude"][:]
lon = dataset.variables["longitude"][:]
wind_u = dataset.variables["windu"][0,:,:][::-1]
wind_v = dataset.variables["windv"][0,:,:][::-1]
max_lat = lat[-1]
min_lon = lon[0]
rows,cols =wind_u.shape
#構造geotransform 0.5是根據latitude和longitude判斷的
geo =(min_lon,0.5,0,max_lat,0,-0.5)
#構造projection
src_srs = osr.SpatialReference()
src_srs.ImportFromEPSG(4326)
src_srs_wkt = src_srs.ExportToWkt()
return wind_u,wind_v,geo,src_srs_wkt,rows,cols
def write_tiff(tiff_file,geo,proj,rows,cols,data_array):
driver = gdal.GetDriverByName("Gtiff")
outdataset = driver.Create(tiff_file,cols,rows,1,gdal.GDT_Float32)
outdataset.SetGeoTransform(geo)
outdataset.SetProjection(proj)
band = outdataset.GetRasterBand(1)
band.WriteArray(data_array)
def nc_to_tif(nc_file,output_dir):
nc_file_name = os.path.basename(nc_file)
output_file_name = os.path.join(output_dir,nc_file_name)
wind_u_file = output_file_name.replace(".nc", ".windu.tif")
wind_v_file = output_file_name.replace(".nc", ".windv.tif")
wind_u, wind_v, geo, proj,rows,cols=extract_nc(nc_file)
write_tiff(wind_u_file,geo,proj,rows,cols,wind_u)
write_tiff(wind_v_file,geo,proj,rows,cols,wind_v)
if __name__ == '__main__':
#風場數據
wind_file = r"D:\result\wind\gfs.wind.forecast.2019112717.nc"
#解析結果存儲路徑
tiff_dir = r"D:\result"
nc_to_tif(wind_file,tiff_dir)