我在这个项目中的目标是从一个大的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 ,请告诉我.此外,我对这一点相对较新,因此如果解释不是最好的,请原谅我,如果有什么需要澄清的,请告诉我.

推荐答案

如果您不介意使用预构建函数,可以使用scipy库:

import numpy as np
from scipy.signal import convolve2d
from scipy.ndimage import label 

## Example matrix
arr = [...]

## Check if neighboring cells are zero using a 2d convolution:
# The kernel
ker = np.array([[0,1,0],
                [1,0,1],
                [0,1,0]])

res = convolve2d(arr,ker,mode='same')

# Eliminate the noise
res = np.int32((res>0)&(arr>0))

# Using label your can segment an image and since an image is basically a matrix:
lab = label(res,ker)

# Get the coordinate of each line.
coord = []
for ii in range(lab[1]):
    coord.append(np.vstack(np.where(lab[0]==(ii+1))))

输出是numpy数组的列表,每行一个数组:

[array([[1, 2, 3, 4, 5, 6, 7, 8],
        [4, 4, 4, 4, 4, 4, 4, 4]], dtype=int64),
 array([[4, 5, 6, 7, 8],
        [7, 7, 7, 7, 7]], dtype=int64)]

这里我使用两个函数:

convolve2d:计算arrker之间的2d卷积.选项mode='same'返回与原始矩阵形状相同的矩阵.

label:分割矩阵,必须考虑的相邻单元由核ker定义.

如果您还想考虑对角线,那么您可以简单地更改内核.

Python相关问答推荐

调查TensorFlow和PyTorch性能的差异

try 从网站获取表(ValueRight:如果使用所有纯量值,则必须传递索引)

在Python中,如何初始化集合列表脚本的输出

在Python中,如何才能/应该使用decorator 来实现函数多态性?

当测试字符串100%包含查询字符串时,为什么t fuzzywuzzy s Process.extractBests不给出100%分数?

Python如何让代码在一个程序中工作而不在其他程序中工作

如何使用Tkinter创建两个高度相同的框架(顶部和底部)?

给定数据点,制定它们的关系

Python中的函数中是否有充分的理由接受float而不接受int?

如何从FDaGrid实例中删除某些函数?

Polars比较了两个预设-有没有方法在第一次不匹配时立即失败

Python上的Instagram API:缺少client_id参数"

如何在类和classy-fastapi -fastapi- followup中使用FastAPI创建路由

如何创建一个缓冲区周围的一行与manim?

部分视图的DataFrame

有没有一种ONE—LINER的方法给一个框架的每一行一个由整数和字符串组成的唯一id?

如何在Pyplot表中舍入值

如何防止Pandas将索引标为周期?

如何在两列上groupBy,并使用pyspark计算每个分组列的平均总价值

用SymPy在Python中求解指数函数