声明2d数组,而不初始化大小和附加操作(Python)


def XY(a):
XY = np.array([])
for i in a:
if (i[1] > 300) and (i[1] < 800) and (i[0] < 375) and (i[0] > 310):
XY = np.append(XY, [i])  
return XY
a = array([[324, 664], [324, 665], [324, 666], [324, 667], [324, 668], [324, 669], [324, 670], [324, 671], [325, 664], [325, 665], [325, 666], [325, 667], [325, 668], [325, 669], [325, 670], [325, 671], [326, 664], [326, 665], [326, 666], [326, 667], [326, 668], [326, 669], [326, 670], [326, 671], [327, 664], [327, 665], [327, 666], [327, 667]])

数组"a"的形状为(num,2(。我希望返回数组的形状与(某个数字,2(相同。但是这个函数返回类似的东西(某个数字,1(。我该怎么修?提前谢谢。

您需要在轴0 上以相同形状附加到ndarray

def XY(a):
XY = np.empty([0, 2], dtype=int)
for i in a:
if 300 < i[1] < 800 and 310 < i[0] < 375:
XY = np.append(XY, [i], axis=0)
return XY
arr = XY(np.array([[324, 664], [324, 665], [324, 666], [324, 667], [324, 668], [324, 669], [324, 670], [324, 671], [325, 664], [325, 665], [325, 666], [325, 667], [325, 668], [325, 669], [325, 670], [325, 671], [326, 664], [326, 665], [326, 666], [326, 667], [326, 668], [326, 669], [326, 670], [326, 671], [327, 664], [327, 665], [327, 666], [327, 667]]))
print(arr.shape)
print(arr)

输出

(28, 2)
[[324 664]
[324 665]
[324 666]
[324 667]
[324 668]
[324 669]
[324 670]
[324 671]
[325 664]
[325 665]
[325 666]
[325 667]
[325 668]
[325 669]
[325 670]
[325 671]
[326 664]
[326 665]
[326 666]
[326 667]
[326 668]
[326 669]
[326 670]
[326 671]
[327 664]
[327 665]
[327 666]
[327 667]]

最新更新