【发布时间】:2020-09-15 14:03:39
【问题描述】:
我正在从 ArcGIS REST API 服务器检索带有元数据的 Sentinel-2 图像。它以字节字符串的形式出现。我目前首先使用 f.write() 将数据写入 tif 文件。然后我用 imageio 打开它,然后用 gdal 将它保存为 geoTIFF。
我想使用 gdal 将图像直接保存为 geoTIFF。但是我还没有弄清楚如何直接从字节数据中将图像提取为numpy数组,或者如何使用gdal直接从字节数据中写入图像。我使用 Python 3.8 和 Windows 10。
import requests
from imageio import imread
from osgeo import gdal
response = requests.get(im_url, auth=auth) # call image url
im_binary = response.content # the image in binary format
im_newpath = 'testimage.tif'
with open(im_newpath, 'wb') as f:
f.write(im_binary)
print(type(im_binary))
print(im_binary[0:50])
返回:
<class 'bytes'>
b'II*\x00\x08\x00\x00\x00\x15\x00\x00\x01\x03\x00\x01\x00\x00\x00X\x02\x00\x00\x01\x01\x03\x00\x01\x00\x00\x00\x90\x01\x00\x00\x02\x01\x03\x00\r\x00\x00\x00\n\x01\x00\x00\x03\x01\x03\x00'
到目前为止,我对数据进行解码的尝试结果不佳。
decoded = im_binary.decode('utf_16')
UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 364-365: illegal UTF-16 surrogate
忽略或替换错误会给出各种非数字字符。有什么建议吗?
【问题讨论】:
-
我看不到,为什么您认为 TIFF 图像二进制数据是 UTF-16 可解码的。 (UTF 只考虑 text)。对于 tiff,需要 pillow 的图像库。
-
我不知道 UTF 只考虑文本,所以这是一个好点。但我最想做的仍然是将字节数据直接写入地理编码图像。枕头不支持超过3个频段,数据有13个频段,这就是我想使用gdal的原因。但我不知道如何使用 gdal 将字节数据写入图像。
-
我还是看不懂,那你说的 decode 是什么意思。如果数据已经是有效的 tiff 图像,则将其写入文件应该如上所述。上面的代码的任何部分都没有涵盖阅读,但看起来,您只需要使用 文件名(而不是原始数据)调用
imread()。 -
我更喜欢更简洁的解决方案,而不是写入文件(到 tif),读取它,然后再次写入(到 geoTIFF)。在我看来,更简洁的解决方案是将请求输出直接写入 geoTIFF。但我还没有找到一种方法来做到这一点。如果我不必在此过程中解码任何内容,那就太好了。
-
尝试 imagecodecs 从编码字节中读取 numpy 数组:
image_array = imagecodecs.tiff_decode(im_binary)
标签: python python-3.x python-requests gis gdal