【发布时间】:2021-11-04 17:35:17
【问题描述】:
从一个包含 1 和 0 的数组中,我试图获取该数组的边界并绘制它。这是我用来获取边界的代码
import numpy as np
import math
import matplotlib.pyplot as plt
binI = np.array([[0,0,0,0,1,0,0,0,0,0,0],
[0,0,0,1,1,1,1,0,0,0,0],
[0,0,1,1,1,1,1,0,0,0,0],
[0,1,1,1,1,0,0,0,0,0,0],
[0,1,1,1,0,0,0,0,0,0,0],
[0,0,1,1,1,1,0,0,0,0,0],
[0,0,0,1,1,1,0,0,0,0,0],
[0,0,0,1,1,0,0,0,0,0,0]])
def boundary_Tracer(arr):
indices_list = []
for i in range (np.shape(arr)[0]):
for j in range (np.shape(arr)[1]):
if arr[i,j] == 1:
if i == 0 and j == 0:
if (arr[i+1,j] == 0) or (arr[i,j+1] == 0):
indices_list.append([i,j])
elif (i == 0) and (j == np.shape(arr)[1]-1):
if (arr[i,j-1] == 0) or (arr[i+1,j] == 0):
indices_list.append([i,j])
elif (i == (np.shape(arr)[0]-1)) and j == 0:
if (arr[i-1,j] == 0) or (arr[i,j+1] == 0):
indices_list.append([i,j])
elif (i == np.shape(arr)[0]-1) and (j == np.shape(arr)[1]-1):
if (arr[i-1,j] == 0) or (arr[i,j-1] == 0):
indices_list.append([i,j])
elif (i in range (1,np.shape(arr)[0]-1)) and (j == 0):
if (arr[i-1,j] == 0) or (arr[i,j+1] == 0) or (arr[i+1,j] == 0):
indices_list.append([i,j])
elif (i in range (1,np.shape(arr)[0]-1)) and (j == np.shape(arr)[1]-1):
if (arr[i-1,j] == 0) or (arr[i,j-1] == 0) or (arr[i+1,j] == 0):
indices_list.append([i,j])
elif (i == 0) and (j in range (1,np.shape(arr)[1]-1)):
if (arr[i,j-1] == 0) or (arr[i,j+1] == 0) or (arr[i+1,j] == 0):
indices_list.append([i,j])
elif (i == np.shape(arr)[0]-1) and (j in range (1,np.shape(arr)[1]-1)):
if (arr[i-1,j] == 0) or (arr[i,j-1] == 0) or (arr[i,j+1] == 0):
indices_list.append([i,j])
else:
if (arr[i-1,j] == 0) or (arr[i+1,j] == 0) or (arr[i,j-1] == 0) or (arr[i,j+1] == 0):
indices_list.append([i,j])
indicies_array = np.array(indices_list)
x_all = indicies_array[:,1]
x_init_bw = np.min(np.where(x_all == np.min(x_all)))
origin = np.reshape(indicies_array[x_init_bw,:],(1,2))[0]
indicies_array = np.vstack((indicies_array,origin))
return indicies_array, origin
bw = boundary_Tracer(binI)[0]
origin = boundary_Tracer(binI)[1]
plt.plot(bw[:,1],bw[:,0])
plt.gca().invert_yaxis()
我知道这很丑,我确信有更好的方法来做到这一点,但这是我最好的。无论如何,当我绘制这个时,情节在点之间曲折。我想让情节只是连接边界而不跨越标有 1 的区域的中间。
用边界的 xy 坐标(bw)重新排列数组的最佳方法是什么?
【问题讨论】:
-
经过一番研究,我找到了一个解释,为什么这是not possible 有一组点,没有更多信息。我希望我的回答能在某种程度上有所帮助。
标签: python arrays sorting coordinates boundary