pyhdf读取和保存hdf文件

参考资料:

pyhdf的安装:https://fhs.github.io/pyhdf/install.html
pyhdf使用:https://fhs.github.io/pyhdf/modules/SD.html

hdf是遥感中常用的文件保存格式,下面我们来介绍一下如何用python读取和保存hdf格式的文件。

一、load pyhdf

# 三种加载方式
import pyhdf.SD 
from pyhdf import SD
from pyhdf.SD import *

二、保存数据

保存hdf文件主要可以分为创建hdf文件与配置文件属性、创建数据集与配置属性、数据集赋值、文件关闭等几个部分。

# Import SD and numpy.
from pyhdf.SD import *
from numpy import *

fileName = 'template.hdf'
# 创建HDF文件
hdfFile = SD(fileName ,SDC.WRITE|SDC.CREATE)

# Assign a few attributes at the file level
hdfFile.author = 'It is me...'
hdfFile.priority = 2

# Create a dataset named 'd1' to hold a 3x3 float array.
d1 = hdfFile.create('d1', SDC.FLOAT32, (3,3))
# Set some attributes on 'd1'
d1.description = 'Sample 3x3 float array'
d1.units = 'celsius'
# Name 'd1' dimensions and assign them attributes.
dim1 = d1.dim(0)
dim2 = d1.dim(1)
dim1.setname('width')
dim2.setname('height')
dim1.units = 'm'
dim2.units = 'cm'

# Assign values to 'd1'
d1[0]  = (14.5, 12.8, 13.0)  # row 1
d1[1:] = ((-1.3, 0.5, 4.8),  # row 2 and
          (3.1, 0.0, 13.8))  # row 3
          
# Close dataset
d1.endaccess()
# Close file
hdfFile.end()

三、读取hdf

获取文件(file)和数据集(dataset)的内容和属性信息

# Import SD and numpy.
from pyhdf.SD import *
from numpy import *

fileName = 'template.hdf'
# Open file in read-only mode (default)
hdfFile = SD(fileName)

# Display attributes.
print "file:", fileName
print "author:", hdfFile.author
print "priority:", hdfFile.priority

# Open dataset 'd1'
d1 = hdfFile.select('d1')

# Display dataset attributes.
print "dataset:", 'd1'
print "description:",d1.description
print "units:", d1.units

# Display dimensions info.
dim1 = d1.dim(0)
dim2 = d1.dim(1)
print "dimensions:"
print "dim1: name=", dim1.info()[0],
print "length=", dim1.length(),
print "units=", dim1.units
print "dim2: name=", dim2.info()[0],
print "length=", dim2.length(),
print "units=", dim2.units

# Show dataset values
print d1[:]
# Close dataset
d1.endaccess()
# Close file
hdfFile.end()

pyhdf的数据格式

CHAR and CHAR8 (equivalent): an 8-bit character.

UCHAR, UCHAR8 and UINT8 (equivalent): unsigned 8-bit values (0 to 255)

INT8: signed 8-bit values (-128 to 127)

INT16: signed 16-bit values

UINT16: unsigned 16 bit values

INT32: signed 32 bit values

UINT32: unsigned 32 bit values

FLOAT32: 32 bit floating point values (C floats)

FLOAT64: 64 bit floating point values (C doubles)

你可能感兴趣的:(##,Python遥感数据处理,python)