gpt4 book ai didi

python - 如何在二维 numpy 数组中查找行?

转载 作者:行者123 更新时间:2023-12-05 04:28:04 26 4
gpt4 key购买 nike

我有一个2D numpy 数组,我想找到水平线和垂直线的边界点

gray_img = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 255, 255, 255, 255, 255, 255, 255, 0],
[0, 255, 255, 255, 255, 255, 255, 255, 0],
[0, 255, 255, 0, 0, 0, 0, 0, 0],
[0, 255, 255, 0, 0, 0, 0, 0, 0],
[0, 255, 255, 0, 0, 0, 0, 0, 0],
[0, 255, 255, 0, 0, 255, 255, 255, 255],
[0, 255, 255, 0, 0, 255, 255, 255, 255],
[0, 255, 255, 0, 0, 0, 0, 0, 0],
[0, 255, 255, 0, 0, 0, 0, 0, 0],
[0, 255, 255, 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, 0, 0, 0, 0, 0]])

desired_outcome = [ [[1,1],[10,1]],
[[1,2],[10,2]],
[[1,3],[2,3]], ...]

以下是我要查找的行:

enter image description here enter image description here

稍后,我想删除较小的线以仅保留距离超过 2 点的线。

最佳答案

垂直线:

m = np.diff(gray_img, 1, 0) # get discrete difference along the 0-axis
m = np.argwhere(m != 0) # get indices where value is not zero
m = m[np.lexsort(m.T)] # sort indices first 1-column then 0-column
m[::2,0] += 1 #

输出:

[[ 1  1]
[10 1]
[ 1 2]
[10 2]
[ 1 3]
[ 2 3]
[ 1 4]
[ 2 4]
[ 1 5]
[ 2 5]
[ 6 5]
[ 7 5]
[ 1 6]
[ 2 6]
[ 6 6]
[ 7 6]
[ 1 7]
[ 2 7]
[ 6 7]
[ 7 7]
[ 6 8]
[ 7 8]]

水平线:

m = np.diff(gray_img, 1, 1, append=np.zeros((gray_img.shape[0], 1)))
m = np.argwhere(m != 0)
m[::2,1] += 1

输出:

[[ 1  1]
[ 1 7]
[ 2 1]
[ 2 7]
[ 3 1]
[ 3 2]
[ 4 1]
[ 4 2]
[ 5 1]
[ 5 2]
[ 6 1]
[ 6 2]
[ 6 5]
[ 6 8]
[ 7 1]
[ 7 2]
[ 7 5]
[ 7 8]
[ 8 1]
[ 8 2]
[ 9 1]
[ 9 2]
[10 1]
[10 2]]

关于python - 如何在二维 numpy 数组中查找行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72681770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com