在 python 中使用 opencv 时断言失败

Assertion failed when use opencv in python

我在 python 的 opencv 中进行相机校准,我遵循了 this page 上的教程。我的代码是完全从页面复制过来的,只是稍微调整了参数。

代码:

import numpy as np
import cv2
import glob

# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2)

# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.

images = glob.glob('../easyimgs/*.jpg')
print('...loading')
for fname in images:
    print(f'processing img:{fname}')
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    print('grayed')
    # Find the chess board corners
    ret, corners = cv2.findChessboardCorners(gray, (8, 11),None)

    # If found, add object points, image points (after refining them)
    if ret == True:
        print('chessboard detected')
        objpoints.append(objp)

        corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
        imgpoints.append(corners2)

        # Draw and display the corners
        img = cv2.drawChessboardCorners(img, (8,11), corners2,ret)
        cv2.namedWindow('img',0)
        cv2.resizeWindow('img', 500, 500)
        cv2.imshow('img',img)
        cv2.waitKey(500)
        cv2.destroyAllWindows()


img2 = cv2.imread("../easyimgs/5.jpg")
print(f"type objpoints:{objpoints[0].shape}")
print(f"type imgpoints:{imgpoints[0].shape}")

ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
h,  w = img2.shape[:2]
newcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
dst = cv2.undistort(img2, mtx, dist, None, newcameramtx)

# crop the image
x,y,w,h = roi
dst = dst[y:y+h, x:x+w]
cv2.namedWindow('result', 0)
cv2.resizeWindow('result', 400, 400)
cv2.imshow('result',dst)

cv2.destroyAllWindows()

但是当我 运行 它时,错误显示为:

Traceback (most recent call last):
  File "*/undistortion.py", line 51, in <module>
    ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
cv2.error: OpenCV(3.4.2) C:\projects\opencv-python\opencv\modules\calib3d\src\calibration.cpp:3143: error: (-215:Assertion failed) ni == ni1 in function 'cv::collectCalibrationData'

Here is my image.


我在网上搜索了一下,很多人也遇到了这个问题。但是博客上的解决方案大多是说这是calibrateCamera()的第一个和第二个参数的类型是objpointsimgpoints造成的。但这些都是 opencv on c++ 的解决方案。

谁能告诉我如何解决python?

objpoints 和 imgpoints 中的条目数必须相同。这个断言意味着他们不是。看起来您正在创建一组 6*7=42 个对象点,用于 6x7 交点的棋盘,但您的实际棋盘有 8*11=88 个交点。因此,当您处理图像时,您的 objpoints 和 imgpoints 列表会获得不同的长度。你需要修改你的objp的creation/initialization有8*11=88个点,坐标对应你棋盘上的真实物理坐标

为此,您需要真正理解您正在使用的代码。放入更多调试语句将帮助您跟踪代码中发生的事情。

请注意,OpenCV 的 Python API 只是 C++ 的包装器 API,因此任何将 OpenCV 与 C++ 结合使用的解决方案(通常)都与 Python也是。