2014-03-12 42 views
2

我是新來的python,我試圖對光柵圖像進行一些簡單的分類。 基本上,我正在讀取TIF圖像作爲二維數組,並對其進行一些計算和操作。對於分類部分,我試圖爲陸地,水域和雲層創建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

您可以乘布爾數組的東西喜歡「和」:

>>> 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,您還可以使用運算符&|達到相同的效果。

+0

hi @wim,我嘗試過,仍然有ValueError ... – user3412669

+0

嘗試像這樣:'土地[(水== 0)&(作物>模式)] = 1' – wim

+0

ohh似乎有用!還有一個questiion,我可以有多個條件使用該表達式?謝謝 – user3412669