我想在 3 个坐标之间切片一个 2D numpy 数组,例如,给定这个 numpy,
[[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]]
和坐标(1,1)(3,1)(3,5),我想要这个:
[[0 0 0 0 0 0 0 0]
[0 1 0 0 0 0 0 0]
[0 1 1 1 0 0 0 0]
[0 1 1 1 1 1 0 0]]
非常感谢任何提示和指南。
我想在 3 个坐标之间切片一个 2D numpy 数组,例如,给定这个 numpy,
[[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]]
和坐标(1,1)(3,1)(3,5),我想要这个:
[[0 0 0 0 0 0 0 0]
[0 1 0 0 0 0 0 0]
[0 1 1 1 0 0 0 0]
[0 1 1 1 1 1 0 0]]
非常感谢任何提示和指南。
np.tri...
函数族的核心函数是np.tri
.
查看它的代码,我们看到它确实如此(对于方形数组):
In [36]: np.greater_equal.outer(np.arange(4),np.arange(+1, 4+1))
Out[36]:
array([[False, False, False, False],
[ True, False, False, False],
[ True, True, False, False],
[ True, True, True, False]])
玩弄我可以生成更接近你的例子的东西:
In [39]: np.greater_equal.outer(np.arange(4),.5*np.arange(+1, 8+1))
Out[39]:
array([[False, False, False, False, False, False, False, False],
[ True, True, False, False, False, False, False, False],
[ True, True, True, True, False, False, False, False],
[ True, True, True, True, True, True, False, False]])
In [40]: _.astype(int)
Out[40]:
array([[0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 0, 0]])
这是否是一种有用的方法取决于您想要的三角形的一般程度。该示例是传统下三角形的变体。但是,如果这些要点更笼统,请说:
(1,1), (3,2), (2,6)
你必须想出一个更复杂的
基于这个答案,我们需要检查三角形的每条边,如果边的方向是逆时针方向,我们可以测试一个点是否位于边的左侧。如果所有边都通过测试 - 点在里面。如果至少有一个失败 - 重点就在外面。
为了测试该点是否(xp, yp)
位于边缘的左侧(x1, y1) - (x2, y2)
,您只需要计算:
D = (x2 - x1) * (yp - y1) - (xp - x1) * (y2 - y1)
如果D > 0
,则该点在左侧。如果D < 0
,则该点在右侧。如果D = 0
,则该点在线上。
这是代码:
def triangular_slicing(input, (x1, y1), (x2, y2), (x3, y3)):
for i in range(input.shape[0]):
for j in range(input.shape[1]):
D = (x2 - x1) * (j - y1) - (i - x1) * (y2 - y1)
if D >= 0:
D = (x3 - x2) * (j - y2) - (i - x2) * (y3 - y2)
if D >= 0:
D = (x1 - x3) * (j - y3) - (i - x3) * (y1 - y3)
if D >= 0:
input[i][j] = 1
return input
结果如下:
a = np.zeros((11, 11), dtype=np.uint)
res = triangular_slicing(a, (1,1), (6,3) , (6,9) )
[[0 0 0 0 0 0 0 0 0 0 0]
[0 1 0 0 0 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0 0 0 0]
[0 0 1 1 1 0 0 0 0 0 0]
[0 0 0 1 1 1 0 0 0 0 0]
[0 0 0 1 1 1 1 1 0 0 0]
[0 0 0 1 1 1 1 1 1 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 0 0 0 0 0 0 0 0]]
a = np.zeros((11, 11), dtype=np.uint)
res = triangular_slicing(a, (0,5), (8,2) , (8,8) )
[[0 0 0 0 0 1 0 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0 0]
[0 0 0 0 1 1 1 0 0 0 0]
[0 0 0 0 1 1 1 0 0 0 0]
[0 0 0 0 1 1 1 0 0 0 0]
[0 0 0 1 1 1 1 1 0 0 0]
[0 0 0 1 1 1 1 1 0 0 0]
[0 0 1 1 1 1 1 1 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]]