From an array with consisted with ones and zeros, I'm trying to get the boundary of that array and plot it. This is the code that I used to get the boundary
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()
I know it's ugly and I'm sure there is a better way to do it but this was my best. Anyways, when I plot this, the plot zigzags between the points. I would like to have the plot just connect the boundaries without crossing over the middle of the area that is marked with 1.
What would be the best way to rearrange array with the xy coordinates of the boundaries (which is bw
)?