如何从tif使用python netCDF4创建netCDF文件?

2024-09-27 00:18:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将带有tif图像的文件夹转换为netcdf

import numpy as np
import datetime as dt
import os
import gdal
import netCDF4
import re
import xarray as xr

#PRIMERA IMAGEN 
ds = gdal.Open("first_image")

a = ds.ReadAsArray()
nlat, nlon = np.shape(a)

b = ds.GetGeoTransform()  # bbox, interval
lon = np.arange(nlon)*b[1]+b[0]
lat = np.arange(nlat)*b[5]+b[3]

#FECHA DE LA PRIMERA IMAGEN
basedate = dt.datetime(2020,10,16,9,0,0)

# Create NetCDF file
nco = netCDF4.Dataset("File.nc",
                      'w', format='NETCDF4')

nco.description = 'Example simulation data'

# Create dimensions, variables and attributes:
nco.createDimension('lon', nlon)
nco.createDimension('lat', nlat)
nco.createDimension('time', None)

timeo = nco.createVariable('time', 'f4', ('time',))
timeo.units = 'hours since 2012-09-28 00:00:00'
timeo.standard_name = 'time'

lono = nco.createVariable('lon', 'f4', ('lon',))
lono.standard_name = 'longitude'

lato = nco.createVariable('lat', 'f4', ('lat',))
lato.standard_name = 'latitude'

# Create short integer variable for temperature data, with chunking
tmno = nco.createVariable('tmn', 'f4',  ('time', 'lat', 'lon'),
                          zlib=True, 
                          fill_value=-9999)
tmno.units = 'degC'
tmno.scale_factor = 1#0.01
tmno.add_offset = 0.00
tmno.long_name = 'minimum monthly temperature'
tmno.standard_name = 'air_temperature'
tmno.set_auto_maskandscale(False)

nco.Conventions = 'CF-1.6'

# Write lon,lat
lono[:] = lon
lato[:] = lat


itime = 0

# Step through data, writing time and data to NetCDF
for root, dirs, files in os.walk(r'folder_images'):
    dirs.sort()
    files.sort()
    for f in files:
        if f[-3:]=='tif':
            print(f)
            # read the time values by parsing the filename
            year = 2012
            mon = 9
            day=28
            hora=int(f[0:2])
            date = dt.datetime(year, mon, day, hora, 0, 0)
            print(date)
            dtime = (date-basedate).total_seconds()/3600
            timeo[itime] = dtime
            # min temp
            tmn_path = os.path.join(root, f)
            print(tmn_path)
            tmn = gdal.Open(tmn_path)
            a = tmn.ReadAsArray()  # data
            tmno[itime, :, :] = a
            itime = itime+1
            tmn=None
nco.close()
ds =None

将netcdf文件添加到Qgis时,坐标错误:

范围 0.5000000000000000,0.5000000000000000:804.5000000000000000000000559.5000000000000000000000

光栅范围为: 范围576172.00000000000000004143175.8648832864128053:616453.81923027604352684171198.0000000000000000

我做错了什么

图像:https://drive.google.com/file/d/13TkWx3UgSyBt48nm0UMC6GJRO_Nwoch6/view?usp=sharing


Tags: nameimportdatatimenpdslonlat

热门问题