首页 > 解决方案 > 有没有办法将 numpy.where() 用于将 NaN 值作为无数据的栅格数据?

问题描述

我有一个栅格数据,其中包含 NaN 值作为无数据。我想从中计算新的栅格,例如 if raster==0 do statement1,if raster==1 do statement2,如果 raster 介于 0 和 1 之间,则 do 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)))))

标签: pythonpython-3.xnumpynanrasterio

解决方案


如果raster是一个数组,

  • raster == x给出一个布尔掩码,其形状与 相同raster,指示 的哪些元素(在您的情况下为像素)raster等于x
  • np.where(arr)arr给出计算结果为 true的数组元素的索引. np.where(raster == x), 因此, 给出像素的索引raster等于x.
  • np.any(arr)当且仅当 的至少一个元素的arr计算结果为 true 时才返回 True。np.any(raster == x),因此,告诉您是否至少有一个像素raster是 x。

假设fvctoaRef_red具有相同的形状并且您想创建一个新emiss的发射数组,如果fvc为 1,则将其设置为 0.99,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
mask = fvc == 0
emiss[mask] = 0.979 - 0.046 * toaRef_red[mask]
mask = (fvc > 0) & (fvc < 1)
emiss[mask] = 0.971 * (1 - fvc[mask]) + 0.987 * fvc[mask]

这与以下内容相同:

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

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


推荐阅读