打印输出时出现问题。我的输出低于

array([[336.34305, 214.00804]], dtype=float32)

而不只是
[[336.34305, 214.00804]]

代码:
import cv2
import numpy as np
chess_img = cv2.imread('board.jpeg')
kernel = np.ones((5,5), np.uint8)
gray = cv2.cvtColor(chess_img,cv2.COLOR_BGR2GRAY)
corners = []
ret , corners = cv2.findChessboardCorners(gray,(7,7), None)
if ret == False:
    print('Did not find')
cv2.drawChessboardCorners(chess_img,(7,7),corners,ret)

def sortFirst(val):
    return val[0][0]
cornersort = corners
print('Corners:')
print(cornersort)
cornersort = sorted(cornersort, key = sortFirst)
print(cornersort)

当我编写另一个代码时,它运行良好:
import numpy as np

arr = [[[2,3]],[[3,7]],[[5,1]]]
def sortSecond(val):
    return val[0][1]
arr = sorted(arr , key = sortSecond)
print(arr)

第一个代码的输出是
[array([[336.34305, 214.00804]], dtype=float32), array([[337.23248,78.57056]], dtype=float32)]

第二个代码的输出是
[[[5, 1]], [[2, 3]], [[3, 7]]]

我希望第一个代码的输出作为第二个代码的输出。请帮忙!

最佳答案

cornersort的每个元素的类型为numpy.ndarray。为了更好地理解这一点,请考虑以下示例:

x = [np.array([[300.34305, 209.00804]], dtype=np.float32), np.array([[336.34305, 214.00804]], dtype=np.float32)]
print(x)
print(type(x[0]))

输出:
[array([[300.34305, 209.00804]], dtype=float32), array([[336.34305, 214.00804]], dtype=float32)]
<type 'numpy.ndarray'>

您可以使用.tolist()获得所需的输出。
cornersort = sorted(cornersort, key = sortFirst)之后添加以下行:
cornersort = [i.tolist() for i in cornersort]

完整代码:
import cv2
import numpy as np

chess_img = cv2.imread('board.jpeg')

gray = cv2.cvtColor(chess_img,cv2.COLOR_BGR2GRAY)
kernel = np.ones((5,5), np.uint8)

corners = []
ret , corners = cv2.findChessboardCorners(gray,(7,6), None)
if ret == False:
    print('Did not find')

cv2.drawChessboardCorners(chess_img,(7,6),corners,ret)

def sortFirst(val):
    return val[0][0]

cornersort = sorted(corners, key = sortFirst)
cornersort = [i.tolist() for i in cornersort]
print(cornersort)

输出:
# print(cornersort[0:10])
[[[146.58010864257812, 240.94161987304688]], [[148.90769958496094, 209.57626342773438]], [[151.7432403564453, 179.90769958496094]], [[154.17581176757812, 152.41171264648438]], [[156.53109741210938, 126.43753051757812]], [[158.8179473876953, 102.08036041259766]], [[161.4022979736328, 78.68504333496094]], [[177.4695281982422, 240.55332946777344]], [[179.25265502929688, 208.77369689941406]], [[180.9288330078125, 179.3069305419922]]]

07-24 09:16