2017-02-24 62 views

回答

1

什麼是在下面的代碼做的是我們使用遞歸來獲取所有相鄰白人從而覆蓋整個「行」。遞歸很容易,我們只需要獲得相鄰的單元格,維護一個校驗數組並完成工作。

接下來我們需要把它們放在2個獨立的數組中。爲此,我們遍歷圖像並將第一個數組傳遞給遞歸函數,如果它的長度爲0,即沒有添加任何內容,否則傳遞第二個數組。

該代碼尚未測試對不起。這也涉及遞歸等概念,並且也有點棘手。如果有任何錯誤或您無法理解任何部分,請在評論中通知我。我會盡早回覆你。謝謝

您的結果座標存儲在arr1和arr2中。

## let image_arr be your 2d image array 

check_arr = numpy.zeros(shape=(rows,cols)) 
arr1 = [] 
arr2 = [] 

def get_neighbour_whites(x,y,arr): 
    def get_adjacent_cells(self, x_coord, y_coord): 
     result = set() 
     for k,l in [(x_coord+i,y_coord+j) for i in (-1,0,1) for j in (-1,0,1) if i != 0 or j != 0]: 
      if k>=0 and k<rows and l>=0 and l<cols: 
       result.add((k,l)) 
     return result 

    check_arr[x,y] = 1 
    arr.append((x,y)) 
    adj_cells = get_adjacent_cells(x,y) 

    for i,j in adj_cells: 
     if image_arr[i,j]==255 and not check_arr[i,j]: 
      get_neighbour_whites(i,j,arr) 

for x in xrange(rows): 
    for y in xrange(cols): 
     if image_arr[x,y] == 255 and not check_arr[x,y]: 
      get_neighbour_whites(x,y,arr1 if len(arr1)==0 else arr2) 
+0

感謝您的迴應,這非常有幫助!幾乎能夠工作,但似乎兩行的所有白色點都存儲在array2中,並且array1中只有一個點,您是否明白爲什麼?還有一個關於你的代碼的問題,當你有'for in in(-1,0,1)'時,爲什麼'(-1,0,1)'?爲什麼'check_arr [x,y]'等於'1'?感謝您的幫助,真正appriciate它:) – agrom

+1

您的歡迎.. check_arr [x,y] = 1意味着我們已經訪問它,因此不需要訪問它再次。這是爲了防止無限遞歸。 –

+1

(-1,0,1)用於相鄰點。看看這個線程更多http://stackoverflow.com/questions/2373306/pythonic-and-efficient-way-of-finding-adjacent-cells-in-grid –

相關問題