如何将栅格dtype从uint8转换为float32?

时间:2020-05-09 18:22:17

标签: python numpy

我想堆叠多个栅格,但其中一些栅格具有float32,而某些栅格栅格则将uint8作为dtype。这给了我这个错误

ValueError:数组的dtype'uint8'与文件的dtype'float32'

不匹配

我使用的代码:

import os
import earthpy.spatial as es
from earthpy.io import path_to_example
band_fnames = ["red.tif", "green.tif", "blue.tif"]
band_paths = [path_to_example(fname) for fname in band_fnames]
destfile = "./stack_result.tif"
arr, arr_meta = es.stack(band_paths, destfile)

有人知道如何解决吗?

1 个答案:

答案 0 :(得分:0)

您可以使用numpy数组的astype方法:

import numpy as np

a = np.array([1, 2], dtype=np.unit8)
a.dtype
>>> dtype('uint8')

b = a.astype(np.float32)
b.dtype
>>> dtype('float32')

# values are the same but now floats
b
>>> array([1., 2.], dtype=float32)

我建议使用上述类似的方法将要堆叠的所有数组转换为相同的dtype