#### Patch counting
def expand_array(square_array):
sh = square_array.shape[0]
new_array = []
new_array.extend([0]*(sh+2))
for i in range(sh):
new_array.append(0)
new_array.extend(square_array[i,:])
new_array.append(0)
new_array.extend([0]*(sh+2))
new_array=np.array(new_array).reshape(sh+2,sh+2)
return new_array
def recursive_find_all_points(i,j,data,point_result,flag):
### if 0, ignore
if data[i,j]==0:
return point_result
### if already considered, continue
if (i,j) in [e for w in point_result.values() for e in w]:
return point_result
### if it's a new patch, count it.
if flag == "origin":
# print('1 block!')
point_result[len(point_result)] = []
point_result[len(point_result)-1].append((i,j))
### recursion in four directions
for direction in [(-1,0),(1,0),(0,-1),(0,1)]:
point_result = recursive_find_all_points(i+direction[0], j+direction[1], data, point_result, flag="derived")
return point_result
def get_patches(array):
"""
Remember to only input 0,1 matrix. Which means only one class is calculated each time.
"""
expanded_array = expand_array(array)
patches = get_points_result(expanded_array)
return patches
写了一个景观生态学“斑块”统计的比较简单的递归算法,每次发现一个斑块(这里指考虑了标准化的正方形区域),向四个方向扩散并判断连接性,直到全部碰壁。然后把这些点放入列表里,避免重复计算。