花式索引中的多重条件

时间:2014-03-12 21:57:32

标签: python arrays numpy multidimensional-array

我是python的新手,我正在尝试对光栅图像进行一些简单的分类。 基本上,我正在读取TIF图像作为2D数组并对其进行一些计算和操作。对于分类部分,我正在尝试为陆地,水和云创建3个空数组。在多个条件下,这些类将被赋值为1,并最终将这些类分别为landclass = 1,waterclass = 2,cloudclass = 3。

显然我可以在一个条件下将数组中的所有值分配给1 像这样:

     crop = gdal.Open(crop,GA_ReadOnly)
     crop = crop.ReadAsArray()
     rows,cols = crop.shape
     mode = int(stats.mode(crop, axis=None)[0])
     water = np.empty(shape(row,cols),dtype=float32)
     land = water
     clouds = water

比我有这样的东西(输出):

     >>> land
     array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
           [ 0.,  0.,  0., ...,  0.,  0.,  0.],
           [ 0.,  0.,  0., ...,  0.,  0.,  0.],
           ..., 
           [ 0.,  0.,  0., ...,  0.,  0.,  0.],
           [ 0.,  0.,  0., ...,  0.,  0.,  0.],
           [ 0.,  0.,  0., ...,  0.,  0.,  0.]], dtype=float32)
     >>> land[water==0]=1
     >>> land
     array([[ 0.,  0.,  0., ...,  1.,  1.,  1.],
            [ 0.,  0.,  0., ...,  1.,  1.,  1.],
            [ 0.,  0.,  0., ...,  1.,  1.,  1.],
            ..., 
            [ 1.,  1.,  1., ...,  0.,  0.,  0.],
            [ 1.,  1.,  1., ...,  0.,  0.,  0.],
            [ 1.,  1.,  1., ...,  0.,  0.,  0.]], dtype=float32)
     >>> land[crop>mode]=1
     >>> land
     array([[ 0.,  0.,  0., ...,  1.,  1.,  1.],
            [ 0.,  0.,  0., ...,  1.,  1.,  1.],
            [ 0.,  0.,  0., ...,  1.,  1.,  1.],
            ..., 
            [ 1.,  1.,  1., ...,  0.,  0.,  0.],
            [ 1.,  1.,  1., ...,  0.,  0.,  0.],
            [ 1.,  1.,  1., ...,  0.,  0.,  0.]], dtype=float32)

但我怎样才能拥有" land"在几个条件下等于1而不改变阵列的形状? 我试着这样做

land[water==0,crop>mode]=1

我得到了ValueError。我试过这个

land[water==0 and crop>mode]=1

和python要求我使用a.all()或a.all()....

对于只有一个条件,结果正是我想要的,我必须这样做才能得到结果。例如(这是我在实际代码中所拥有的):

water[band6 < b6_threshold]=1
water[band7 < b7_threshold_1]=1
water[band6 > b6_threshold]=1
water[band7 < b7_threshold_2]=1

land[band6 > b6_threshold]=1
land[band7 > b7_threshold_2]=1
land[clouds == 1]=1
land[water == 1]=1
land[b1b4 < 0.5]=1
land[band3 < 0.1)]=1    

clouds[land == 0]=1
clouds[water == 0]=1
clouds[band6 < (b6_mode-4)]=1

我发现这有点令人困惑,我想在一个声明中结合所有条件......有什么建议吗?

非常感谢!

1 个答案:

答案 0 :(得分:1)

您可以将布尔数组乘以“and”:

>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> a[(a > 1) * (a < 3)] = 99
>>> a
array([ 1, 99,  3,  4])

您可以将它们添加为“或”:

>>> a[(a > 1) + (a < 3)] = 123
>>> a
array([123, 123, 123, 123])

或者,如果您更喜欢考虑布尔逻辑而不是True和False为0和1,您也可以使用运算符&|来实现相同的效果。