我在这个项目中的目标是从一个大的2d数组开始,并将其分为多个array.这是原始数组:
arr = np.array([[0,0,0,0,0,0,0,0,0],
[0,0,0,0,1,0,0,0,0],
[0,1,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,1,0],
[0,0,0,0,1,0,0,1,0],
[0,1,0,0,1,0,0,1,0],
[0,0,0,0,1,0,0,1,0],
[0,0,0,0,1,0,0,1,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]])
该数组表示两条垂直线(一条线的长度为8,另一条线的长度为5).其他两个1被视为错误.首先,我使用这段代码消除了错误.它的工作是判断相邻像素/单元格,如果所有相邻单元格都为零,则将其更改为零.
noise = []
for i, e in enumerate(data):
if arr[e[1],e[0]+1] == 0 and arr[e[1],e[0]-1] == 0 and arr[e[1]-1,e[0]] == 0 and arr[e[1]+1,e[0]] == 0 \
and arr[e[1]+1,e[0]+1] == 0 and arr[e[1]+1,e[0]-1] == 0 and arr[e[1]-1,e[0]+1] == 0 and arr[e[1]-1,e[0]-1] == 0:
noise.append(i)
data = np.delete(data, noise, axis = 0)
接下来,我想把数组分成两个子数组,其中子数组1是第一行的x,y坐标(列,行),子数组2是第二行的x,y坐标.为此,我首先做了一个循环,记录了两条线端点的位置.我使用了一个类似于查找和删除单个像素/噪声的循环.
最后,一旦我有了端点坐标数组,我做了一个循环,从一个端点开始,判断下一个像素的方向,附加坐标,然后重复.下面你可以找到我用来做这个的循环.
allfibers = []
end_points = np.array(end_points)
for i, e in enumerate(end_points):
fiber = []
row = data[end_points[i]][1]
column = data[end_points[i]][0]
fiber.append([row,column])
_ = 0
z = f'start -> row, column = {row}, {column}'
while True:
print(z)
if arr[row][column+1] == 1 and z !='left': #right of pix
fiber.append([row,column+1])
column += 1
z = 'right'
elif arr[row][column-1] == 1 and z !='right': #left of pix
fiber.append([row,column-1])
column -= 1
z = 'left'
elif arr[row+1][column] == 1 and z !='down': #above pix
fiber.append([row+1,column])
row += 1
z = 'up'
elif arr[row-1][column] == 1 and z !='up': #below pix
fiber.append([row-1,column])
row -= 1
z = 'down'
if (np.any(endpoint_coord) == np.all([row,column]) or np.any(endpoint_coord) ==
np.all([row,column-1]) \
or np.any(endpoint_coord) == np.all([row-1,column])) and _ > 1:
break
_ += 1
allfibers.append(np.array(fiber))
data_type = np.dtype(np.int64)
allfibers = np.array(allfibers, dtype=data_type)
print(allfibers)
`
问题就在这段代码的正上方.程序返回:
[[[1 4]
[2 4]
[3 4]
[4 4]]
[[4 7]
[5 7]
[6 7]
[7 7]]
[[8 4]
[7 4]
[6 4]
[5 4]]
[[8 7]
[7 7]
[6 7]
[5 7]]]
这个问题不是因为原始数组中有4个子数组,只有2行.因为每根光纤都有两个端点,所以这是预期的,并且可以在以后轻松处理.问题是长度不匹配.我不知道为什么会这样.如果有人对如何解决这个问题有任何 idea ,请告诉我.此外,我对这一点相对较新,因此如果解释不是最好的,请原谅我,如果有什么需要澄清的,请告诉我.