使用python gdal从字节数据保存图像

问题描述 投票:0回答:1

我正在从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

忽略或替换错误会给出各种非数字字符。有什么建议吗?

python python-3.x python-requests gis gdal
1个回答
0
投票

总结我对评论的评论和见解:

该方法似乎没有错。由于图像由纯二进制数据组成,因此不使用UTF解码例程。

我不了解其他解码的必要性。收到的内容看起来像是很好的TIFF数据。

虽然仅为了能够将文件传递到另一个库而写一个临时文件似乎很笨拙,但这是一种可靠而干净的方法。可能可以通过使用StringIo实例来避免物理文件,但是由于这需要将完整的图像数据保存在内存中,因此它可能不适用于大型图像。 (在这种情况下,我不确定要传递给tom imread()的URL的样子-似乎还有一个参数可以使用file代替。)

© www.soinside.com 2019 - 2024. All rights reserved.