当在光栅数据集上应用多边形掩码时,我在处理Python的rasterio包中没有数据值时遇到了困难。这个特殊的栅格是具有7个波段的Landsat uint8,由于255是无数据的保留值,因此没有内在地指定no数据值。但是,有时uint8数据是从uint16数据中压缩出来的,而255个值是一个有效的数据值,我不想将其视为“无数据”(数据是全位范围的)。rasterio的掩码函数的缺省值是,如果没有指定这个参数,则将0视为'no data‘值,这与使用相同的方式存在问题,因为0有时被认为是一个有效的数据值。有什么方法可以覆盖“无数据”的元数据值吗?
我尝试了几种不同的方法来解决这个问题(详见下文),但都没有成功。
import rasterio
import fiona
import numpy as np
fp_src = ''
fp_dst = ''
shape = ''
# get shapes
with fiona.open(shape, 'r') as shapefile:
geoms = [feature['geometry'] for feature in shapefile]
# Method Number 1
# ~~~~~~~~~~~~~~~~~~~~~~~~~
# open original raster, copy meta & alter dtype
with rasterio.open(fp_src) as src_dataset:
kwds = src_dataset.profile
kwds['dtype'] = 'uint16'
src_meta = src_dataset.meta
# write a new raster with the copied and altered meta
with rasterio.open(fp_dst, 'w', **kwds) as dst_dataset:
dst_meta = dst_dataset.meta
src_dataset.close()
dst_dataset.close()
img = rasterio.open(fp_dst)
# mask img and set nodata to 256 (out of the uint8 range)
out_image, out_transform = mask(img, geoms, nodata=256)
# out_image output: values outside of the geoms are 256 & values inside are 0.
# Method Number 2
# ~~~~~~~~~~~~~~~~~~~~~~~~~
# open original raster, copy meta & alter dtype
with rasterio.open(fp_src) as src_dataset:
kwds = src_dataset.profile
kwds['nodata'] = np.nan
kwds['dtype'] = 'uint16'
src_meta = src_dataset.meta
# write a new raster with the copied and altered meta
with rasterio.open(fp_dst, 'w', **kwds) as dst_dataset:
dst_meta = dst_dataset.meta
src_dataset.close()
dst_dataset.close()
img = rasterio.open(fp_dst)
# mask img and let the mask function default to the image's newly created nodata (np.nan from inside with rastario.open...)
out_image, out_transform = mask(img, geoms)
# out_image output: nodata value, nan, is beyond the valid range of its data type
# Method Number 3
# ~~~~~~~~~~~~~~~~~~~~~~~~~
# mask img and set nodata to nan
out_image, out_transform = mask(fp_src, geoms, nodata=np.nan)
# out_image output: Cannot convert fill_value nan to dtype.我希望看到在给定多边形之外的所有像素被转换为“无数据”条目,该条目不一定是有效范围的一部分,这样脚本就不可能意外地将有效值视为无数据。
发布于 2020-04-02 09:31:05
问题是np.nan是一个不能转换为整数的浮点数。下面是我解决这个问题的方法:
with rasterio.open(fp_src) as src_dataset:
meta = src_dataset.meta
meta.update(
{
"nodata": np.iinfo(src_dataset.dtypes[0]).max
}
)
data = src_dataset.read()
with rasterio.open(fp_dst, 'w', **meta) as dst_dataset:
dst_dataset.write(data)函数np.iinfo(dtype).max查找给定整数类型的最大值。我将此方法用于具有1波段的数据集,因此它也应与您的数据一起工作。如果没有的话请告诉我。
https://stackoverflow.com/questions/57245971
复制相似问题