读取数据(简答题)
在确定了网格的大小(n_rows
xn_cols
= 448x304)后,您可以使用numpy.frombuffer
简单地读取数据。
import numpy as np
dt = np.dtype(('>u1', (n_rows, n_cols)))
x = np.frombuffer(filecontent[300:], dt)
x = x[0,:,:]
'>u1'
指定了数据的格式,本例中为1字节大小的无符号整数,其大端格式。
使用matplotlib.pyplot
绘制此图。
import matplotlib.pyplot as plt
plt.imshow(x, extent=[0,3,-3,3], aspect="auto")
plt.show()
"
extent=
选项仅指定轴值,您可以将其更改为例如经度/纬度(从标题解析)"
![Output](https://istack.dev59.com/TtoaP.webp)
.unpack()的错误解释
从struct.unpack(fmt, string)
的文档中可以得知:
字符串必须恰好包含格式所需的数据量(len(string)
必须等于calcsize(fmt)
)。
您可以通过查看格式字符部分来确定格式字符串(fmt
)中指定的大小。
在struct.unpack("iiii",filecontent[:300])
中,您的fmt
指定了4个int类型(您也可以使用4i
=iiii
来简化),每个类型的大小为4,需要一个长度为16的字符串。
而您的字符串(filecontent[:300]
)长度为300,而您的fmt
要求一个长度为16的字符串,因此出现了错误。
.unpack()的使用示例
作为例子,阅读您提供的文档,我提取了前21*6字节,其格式如下:
一个由21个6字节字符字符串组成的数组,其中包含有极地立体投影网格特征等信息。
使用:
x = struct.unpack("6s"*21, filecontent[:126])
这将返回一个由21个元素组成的元组。注意某些元素中的空格填充以满足6字节的要求。
>> print x
注:
- 第一个参数
fmt
,"6s"*21
是一个字符串,其中6s
重复了21次。每个格式字符6s
表示一个6字节的字符串(见下文),这将匹配您文档中指定的所需格式。
filecontent[: 126]
中的数字126
计算为6*21 = 126
。
- 请注意,在
s
(字符串)说明符中,前面的数字不表示要重复格式字符6次(因为对于其他格式字符通常会这样做)。相反,它指定了字符串的大小。s
表示1字节字符串,而6s
表示6字节字符串。
更详细的标头读取解决方案(长)
由于必须手动指定二进制数据,因此在源代码中可能很繁琐。您可以考虑使用一些配置文件(如.ini
文件)。
这个函数将读取头文件并将其存储在一个字典中,其中结构是从一个
.ini
文件中给定的。
import ConfigParser
def read_header(data, config_file):
"""
Read binary data specified by a INI file which specifies the structure
"""
with open(config_file) as fd:
conf = ConfigParser.ConfigParser()
conf.readfp(fd)
header = {}
for key in conf.options('structure'):
start_idx, end_idx = [int(x) for x in conf.get('structure', key).split(',')]
start_idx -= 1
strLength = end_idx - start_idx
header[key] = struct.unpack("%is" % strLength, data[start_idx:end_idx])
header[key] = [x.strip() for x in header[key]]
header[key] = [x.replace('\x00', '') for x in header[key]]
header = {k:v[0] for k, v in header.iteritems()}
return header
下面是一个示例的
.ini
文件。键是存储数据时使用的名称,值是由逗号分隔的一对值,第一个值是起始索引,第二个值是结束索引。
这些值来自于你文档中的表1。
[structure]
missing_data: 1, 6
n_cols: 7, 12
n_rows: 13, 18
latitude_enclosed: 25, 30
这个函数可以按以下方式使用:
header = read_header(filecontent, 'headerStructure.ini')
n_cols = int(header['n_cols'])
x = struct.unpack("75i", filecontent[:300])
? - Aemyl