有什么方法可以对包含NaN值的无数据的栅格数据使用numpy.where()?

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

我有一个栅格数据,其中包含NaN值作为无数据。我想用它计算新的栅格数据,比如如果栅格==0,做statement1,如果栅格==1,做statement2,如果栅格在0和1之间,做statement3,否则不改变值。我如何使用numpy.where()函数来实现这个目标?

这是我的代码。

import os
import rasterio
from rasterio import plot
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

os.listdir('../NDVI_output')

ndvi1 = rasterio.open("../NDVI_output/NDVI.tiff")

min_value = ndvi_s = np.nanmin(ndvi) #NDVI of Bare soil
max_value = ndvi_v = np.nanmax(ndvi) #NDVI of full vegetation cover

fvc = (ndvi-ndvi_s)/(ndvi_v-ndvi_s) #fvc: Fractional Vegetation Cover

band4 = rasterio.open('../TOAreflectance_output/TOAref_B4.tiff')
toaRef_red = band4.read(1).astype('float64')
emiss = np.where((fvc == 1.).any(), 0.99,
                 (np.where((fvc == 0.).any(), 0.979-0.046*toaRef_red,
                           (np.where((0.<fvc<1.).any(), 0.971*(1-fvc)+0.987*fvc, fvc)))))
python python-3.x numpy nan rasterio
1个回答
0
投票

语句3,...。raster 是一个数组。

  • raster == x 给出一个布尔掩码,其形状与 raster的哪些元素(在你的例子中是像素)。raster 等于 x
  • np.where(arr) 给出了数组中元素的索引 arr 的值为真。np.where(raster == x)因此,给出了像素在 raster 等于 x.
  • np.any(arr) 如果且仅如果至少有一个元素是 arr 评估为真。np.any(raster == x)因此,告诉你是否有至少一个像素的 raster 是x。

假设 fvctoaRef_red 具有相同的形状,而你想创建一个新的数组。emiss 排放,如果是,则设置为0.99。fvc 是1,到 0.979 - 0.046 * toaRef_red 如果 fvc 是0,到 0.971 * (1 - fvc) + 0.987 * fvc 如果0 < fvc < 1,否则为NaN,你可以做如下操作。

emiss = np.full(ndvi.shape, np.nan)    # create new array filled with nan
emiss[fvc == 1] = 0.99
emiss[fvc == 0] = 0.979 - 0.046 * toaRef_red
emiss[(fvc > 0) & (fvc < 1)] = 0.971 * (1 - fvc) + 0.987 * fvc

这跟..:

emiss = np.full(ndvi.shape, np.nan)    # create new array filled with nan
emiss[np.where(fvc == 1)] = 0.99
emiss[np.where(fvc == 0)] = 0.979 - 0.046 * toaRef_red
emiss[np.where((fvc > 0) & (fvc < 1))] = 0.971 * (1 - fvc) + 0.987 * fvc

后者显然是多余的。你不需要 np.where 在这里。

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