在python中使用opencv时断言失败

问题描述 投票:0回答:1

我正在使用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的第一个和第二个参数的类型引起的。但这些都是c ++上opencv的解决方案。

谁能告诉我如何在python中解决它?

python opencv camera-calibration distortion
1个回答
0
投票

objpoints和imgpoints中的条目数必须相同。这种说法意味着它们不是。看起来你正在创建一组6 * 7 = 42个objpoints,用于6x7交叉的棋盘,但你的实际棋盘有8 * 11 = 88个交叉点。因此,当您处理图像时,您的objpoints和imgpoints列表会有不同的长度。您需要修改objp的创建/初始化,使其具有8 * 11 = 88个点,其坐标对应于棋盘上的实际物理坐标。

要做到这一点,您需要真正理解您正在使用的代码。添加更多调试语句将帮助您跟踪代码中发生的情况。

请注意,OpenCV的Python API只是C ++ API的包装,因此任何使用OpenCV和C ++的解决方案(通常)都与Python相关。

© www.soinside.com 2019 - 2024. All rights reserved.