簡體   English   中英

在numpy 2D矩陣中計算“孔”

[英]Counting “wells” in a numpy 2D matrix

給定1s和0s的2D矩陣,例如-

array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
       [0, 1, 1, 0, 0, 1, 0, 1, 0, 1],
       [1, 1, 0, 0, 1, 1, 0, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 0, 1, 0, 0],
       [1, 0, 0, 0, 1, 0, 1, 1, 0, 0],
       [1, 0, 0, 0, 1, 0, 1, 1, 1, 0],
       [1, 0, 0, 0, 1, 1, 0, 1, 1, 0]])

1表示塊,0表示空白。 我想計算一下數量及其累積深度

當一列短於其相鄰兩列時,就存在一口井,假定邊界被塊(1s)填充。 例如,填充邊框,數組變為:

array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
       [1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1],
       [1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1],
       [1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1],
       [1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1],
       [1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1]])
  • 孔數為3第1列,第4列和(9,10) )。

  • 孔的深度是min(height(col_to_left), height(col_to_right)) - height(well_col)
    因此,在這種情況下,深度為[ 1,1,7 ] 因此,累積深度為1 + 1 + 7 = 9

我將如何找到這個? 我想避免使用循環。

您可以使用argmax獲取每列中第一個的位置。

# find absolute depths
d = X.argmax(0)
# correct columns that are all zero
v = np.take_along_axis(X, d[None], 0)
d[v[0]==0] = len(X)
# pad and compute the col to next col changes
d = np.diff(np.concatenate([[0], d, [0]]))
# exclude no change
chng, = np.where(d)
# find down changes
dwn = d[chng]>0
# wells are where we go down and the next non zero change is up
well = dwn[:-1]&~dwn[1:]
# map back to unfiltered indices for left and right walls
l, r = chng[:-1][well], chng[1:][well]
wells = np.c_[l+1, r]
wells
# array([[ 1,  1],
#       [ 4,  4],
#       [ 9, 10]])
# retrieve relative depths
depths = np.minimum(d[l], -d[r])
depths
# array([1, 1, 7])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM