使用 Python 和 OpenCV 错误校准网络摄像头
Calibrating Webcam using Python and OpenCV Error
对这一切都很陌生,我正在尝试按照 this 指南并使用下面的代码对网络摄像头进行校准。我收到以下错误 ..
OpenCV Error: Assertion failed (ni > 0 && ni == ni1) in collectCalibrationData, file /build/buildd/opencv-2.4.8+dfsg1/modules/calib3d/src/calibration.cpp, line 3193
cv2.error: /build/buildd/opencv-2.4.8+dfsg1/modules/calib3d/src/calibration.cpp:3193: error: (-215) ni > 0 && ni == ni1 in function collectCalibrationData
谁能解释一下这个错误是什么以及如何解决?
(底部完全错误)
import numpy as np
import cv2
import glob
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world
imgpoints = [] # 2d points in image plane.
images = glob.glob('*.png')
objp = np.zeros((6*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2)
objp = objp * 22
for fname in images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret = False
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(gray, (6,9))
# If found, add object points, image points (after refining them)
if ret == True:
objpoints.append(objp)
cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria)
imgpoints.append(corners)
# Draw and display the corners
cv2.drawChessboardCorners(img, (6,9), corners, ret)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.waitKey(0)
for i in range (1,5):
cv2.waitKey(1)
cv2.destroyAllWindows()
cv2.waitKey(1)
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
OpenCV Error: Assertion failed (ni > 0 && ni == ni1) in collectCalibrationData, file /build/buildd/opencv-2.4.8+dfsg1/modules/calib3d/src/calibration.cpp, line 3193
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "/home/students/Test/test.py", line 49, in
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
cv2.error: /build/buildd/opencv-2.4.8+dfsg1/modules/calib3d/src/calibration.cpp:3193: error: (-215) ni > 0 && ni == ni1 in function collectCalibrationData
所以我发现错误是由于 imgpoints 是一个 1 长数组,而它应该与 objpoints 一样长。我发现,如果您使用一张图像,则可以将校准函数中的 imgpoints 直接替换为角落。希望对遇到同样错误的人有所帮助。
(在此过程中进行了一些更改,并且仍在尝试修复它以使用多个图像)
import numpy as np
import cv2
import glob
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Arrays to store object points and image points from all the images.
imgpoints = [] # 2d points in image plane.
images = glob.glob('*.png')
for fname in images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret = False
# Find the chess board c orners
ret, corners = cv2.findChessboardCorners(gray, (6,9))
# If found, add object points, image points (after refining them)
if ret == True:
cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria)
imgpoints.append(corners)
# Draw and display the corners
cv2.drawChessboardCorners(img, (6,9), corners, ret)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.waitKey(0)
for i in range (1,5):
cv2.waitKey(1)
cv2.destroyAllWindows()
cv2.waitKey(1)
imgpoints = np.array(imgpoints,'float32')
print len(corners), len(pattern_points)
pattern_size = (9, 6)
pattern_points = np.zeros( (np.prod(pattern_size), 3), np.float32)
pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2).astype(np.float32)
pattern_points = np.array(pattern_points,dtype=np.float32)
ret, matrix, dist_coef, rvecs, tvecs = cv2.calibrateCamera([pattern_points], [corners], gray.shape[::-1], flags=cv2.CALIB_USE_INTRINSIC_GUESS)
深入研究源代码:
for( i = 0; i < nimages; i++, j += ni )
{
Mat objpt = objectPoints.getMat(i);
Mat imgpt1 = imagePoints1.getMat(i);
ni = objpt.checkVector(3, CV_32F);
int ni1 = imgpt1.checkVector(2, CV_32F);
CV_Assert( ni > 0 && ni == ni1 );
...
这:Assertion failed (ni > 0 && ni == ni1)
表示您的对象点 array 的长度为零,或者对象和图像数组的大小不同。
需要明确的是:calibrateCamera()
不仅希望提供一个对象点数组和另一个图像点数组,而且还提供一个 图像和对象点数组数组。如果您只有一个图像(因此只有一对图像和对象点),您可以将这些数组包裹在一组方括号中:
obj = [[x, y, z], [x1, y1, z1]] # wrong
img = [[x, y], [x1, y1]] # wrong
obj = [[[x, y, z], [x1, y1, z1]]] # right
img = [[[x, y], [x1, y1]]] # right
回想起我自己第一次学习本教程时,看起来您唯一更改的是文件扩展名(从 jpg 到 png),这表明您正在使用自己的资源 - 因此您的问题可能在于您使用的图像数量。我认为您正在使用的 image/images 可能没有成功选择棋盘 - 因此您的对象点数组永远不会添加任何内容。尝试打印 运行 calibrateCamera
之前的数组,并可能使用 /samples/cpp
中提供的棋盘图像
我遇到了同样的问题,你的主要错误(我知道是因为我自己犯的)是你改变了棋盘大小(示例中默认为 7x6,你的是 6x9),但是你忽略了改变例程顶部初始化代码中的大小
objp = np.zeros((6*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2)
要使其适用于多种棋盘尺寸,您可以像这样调整代码:
# checkerboard Dimensions
cbrow = 5
cbcol = 7
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((cbrow * cbcol, 3), np.float32)
objp[:, :2] = np.mgrid[0:cbcol, 0:cbrow].T.reshape(-1, 2)
.
.
.
ret, corners = cv2.findChessboardCorners(gray, (cbcol, cbrow), None)
谢谢@s-low!您的源代码非常有用。
另一个初学者可能犯的错误是objp的数据类型。
当我分配 objp = np.zeros((6*7,3), np.float32)
时,我忽略了数据类型分配。在python 2.7中,默认的dtype
是float64
。所以,当代码调用函数'cv2.calibrateCamera
'时,出现了类似的断言错误:
OpenCV Error: Assertion failed (ni >= 0) in collectCalibrationData, file /Users/jhelmus/anaconda/conda-bld/work/opencv-2.4.8/modules/calib3d/src/calibration.cpp, line 3169
所以,只是源代码ni = objpt.checkVector(3, CV_32F)
给了我一个线索,objp的矩阵必须分配给float32
。
我遇到了同样的问题,经过一番研究后,我在此处的答案中发现了问题。
我解决了它改变 objp
:
的形状
objp = objp.reshape(-1,1,3)
我还有另一个问题:findChessboardCorners
找到的角点数可能小于 7*6(图案大小)所以我只保留找到的角点数 3D 点:
corners2 = cv2.cornerSubPix(image=gray, corners=corners,
winSize=(11,11), zeroZone=(-1,-1),
criteria=(cv2.TERM_CRITERIA_EPS +
cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001))
imgpoints.append(corners2)
objpoints.append(objp[0:corners2.shape[0]])
在那之后代码工作正常 :D
编辑:我意识到如果不使用 retval
(真或假)我们检查 corners
不是 None
。
如果您遵循以下示例:
那么,问题就很好解决了,因为函数:
Corners2 = cv2.cornerSubPix(灰色,角,(11,11),(-1,1),标准)
在当前版本的opencv中returns为空
这个也是:
img = cv2.drawChessboardCorners (img, (7.6), corners2, ret)
所以你所要做的就是更改那些代码行,这是我改编的代码:
from webcam import Webcam
import cv2
from datetime import datetime
import numpy as np
webcam = Webcam()
webcam.start()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
objp = np.zeros((6*9,3), np.float32)
objp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2)
objpoints = []
imgpoints = []
i = 0
while i < 10:
image = webcam.get_current_frame()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, (9,6), None)
print ret
if ret == True:
cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
imgpoints.append(corners)
objpoints.append(objp)
cv2.drawChessboardCorners(image, (9,6), corners,ret)
i += 1
cv2.imshow('grid', image)
cv2.waitKey(1000)
cv2.destroyAllWindows()
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
np.savez("webcam_calibration_ouput_2", ret=ret, mtx=mtx, dist=dist, rvecs=rvecs, tvecs=tvecs)
网络摄像头class:
import cv2
from threading import Thread
class Webcam:
def __init__(self):
self.video_capture = cv2.VideoCapture(0)
self.current_frame = self.video_capture.read()[1]
# create thread for capturing images
def start(self):
Thread(target=self._update_frame, args=()).start()
def _update_frame(self):
while(True):
self.current_frame = self.video_capture.read()[1]
# get the current frame
def get_current_frame(self):
return self.current_frame
请注意,数字 6 和 9 可能会根据您的国际象棋的尺寸而变化,我的国际象棋的尺寸是 10x7。
我在输入自己用手机相机拍摄的 jpg 图片时遇到了同样的问题。最初,当我只是 运行 您分享的 link 中可用的代码时,我发现 rect
总是设置为 FALSE
。后来我发现我输入的是棋盘的确切大小,这使得代码无法识别棋盘图案。我的意思是我使用了大小为 8X6
的棋盘并在代码中输入了 8X6
,例如如下所示
objp = np.zeros((6*8,3), np.float32)
objp[:,:2] = np.mgrid[0:8,0:6].T.reshape(-1,2)
因为它无法识别模式,当我将行和列维度分别减少 1(或超过一,在我的例子中,它是 7X5
)然后繁荣,我得到了打印图像作为输出的参数。
objp = np.zeros(((5*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:5].T.reshape(-1,2)
此外,如果您将此文档用于 OpenCV 3.0 beta doc there's a minor change that might need to be rectified, the difference of which you can spot by going here
我遇到了同样的问题,导致断言失败(ni > 0 && ni == ni1);
我认为应该了解第一个答案中讨论过的 ni 和 ni1 的真正含义。 objectpoints 和 imagepoints 应该是完全相同的大小。无论垫子的数量或垫子的大小。
对我来说,我的问题是我有 5 个垫子用于图像点和对象点,而对于垫子的大小,图像点为 36*2,而对象点为 48*3。所以我说它们应该完全一样,除了一个是point2f,另一个是point3f。
对这一切都很陌生,我正在尝试按照 this 指南并使用下面的代码对网络摄像头进行校准。我收到以下错误 ..
OpenCV Error: Assertion failed (ni > 0 && ni == ni1) in collectCalibrationData, file /build/buildd/opencv-2.4.8+dfsg1/modules/calib3d/src/calibration.cpp, line 3193
cv2.error: /build/buildd/opencv-2.4.8+dfsg1/modules/calib3d/src/calibration.cpp:3193: error: (-215) ni > 0 && ni == ni1 in function collectCalibrationData
谁能解释一下这个错误是什么以及如何解决?
(底部完全错误)
import numpy as np
import cv2
import glob
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world
imgpoints = [] # 2d points in image plane.
images = glob.glob('*.png')
objp = np.zeros((6*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2)
objp = objp * 22
for fname in images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret = False
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(gray, (6,9))
# If found, add object points, image points (after refining them)
if ret == True:
objpoints.append(objp)
cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria)
imgpoints.append(corners)
# Draw and display the corners
cv2.drawChessboardCorners(img, (6,9), corners, ret)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.waitKey(0)
for i in range (1,5):
cv2.waitKey(1)
cv2.destroyAllWindows()
cv2.waitKey(1)
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
OpenCV Error: Assertion failed (ni > 0 && ni == ni1) in collectCalibrationData, file /build/buildd/opencv-2.4.8+dfsg1/modules/calib3d/src/calibration.cpp, line 3193 Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile execfile(filename, namespace) File "/home/students/Test/test.py", line 49, in ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None) cv2.error: /build/buildd/opencv-2.4.8+dfsg1/modules/calib3d/src/calibration.cpp:3193: error: (-215) ni > 0 && ni == ni1 in function collectCalibrationData
所以我发现错误是由于 imgpoints 是一个 1 长数组,而它应该与 objpoints 一样长。我发现,如果您使用一张图像,则可以将校准函数中的 imgpoints 直接替换为角落。希望对遇到同样错误的人有所帮助。
(在此过程中进行了一些更改,并且仍在尝试修复它以使用多个图像)
import numpy as np
import cv2
import glob
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Arrays to store object points and image points from all the images.
imgpoints = [] # 2d points in image plane.
images = glob.glob('*.png')
for fname in images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret = False
# Find the chess board c orners
ret, corners = cv2.findChessboardCorners(gray, (6,9))
# If found, add object points, image points (after refining them)
if ret == True:
cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria)
imgpoints.append(corners)
# Draw and display the corners
cv2.drawChessboardCorners(img, (6,9), corners, ret)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.waitKey(0)
for i in range (1,5):
cv2.waitKey(1)
cv2.destroyAllWindows()
cv2.waitKey(1)
imgpoints = np.array(imgpoints,'float32')
print len(corners), len(pattern_points)
pattern_size = (9, 6)
pattern_points = np.zeros( (np.prod(pattern_size), 3), np.float32)
pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2).astype(np.float32)
pattern_points = np.array(pattern_points,dtype=np.float32)
ret, matrix, dist_coef, rvecs, tvecs = cv2.calibrateCamera([pattern_points], [corners], gray.shape[::-1], flags=cv2.CALIB_USE_INTRINSIC_GUESS)
深入研究源代码:
for( i = 0; i < nimages; i++, j += ni )
{
Mat objpt = objectPoints.getMat(i);
Mat imgpt1 = imagePoints1.getMat(i);
ni = objpt.checkVector(3, CV_32F);
int ni1 = imgpt1.checkVector(2, CV_32F);
CV_Assert( ni > 0 && ni == ni1 );
...
这:Assertion failed (ni > 0 && ni == ni1)
表示您的对象点 array 的长度为零,或者对象和图像数组的大小不同。
需要明确的是:calibrateCamera()
不仅希望提供一个对象点数组和另一个图像点数组,而且还提供一个 图像和对象点数组数组。如果您只有一个图像(因此只有一对图像和对象点),您可以将这些数组包裹在一组方括号中:
obj = [[x, y, z], [x1, y1, z1]] # wrong
img = [[x, y], [x1, y1]] # wrong
obj = [[[x, y, z], [x1, y1, z1]]] # right
img = [[[x, y], [x1, y1]]] # right
回想起我自己第一次学习本教程时,看起来您唯一更改的是文件扩展名(从 jpg 到 png),这表明您正在使用自己的资源 - 因此您的问题可能在于您使用的图像数量。我认为您正在使用的 image/images 可能没有成功选择棋盘 - 因此您的对象点数组永远不会添加任何内容。尝试打印 运行 calibrateCamera
之前的数组,并可能使用 /samples/cpp
我遇到了同样的问题,你的主要错误(我知道是因为我自己犯的)是你改变了棋盘大小(示例中默认为 7x6,你的是 6x9),但是你忽略了改变例程顶部初始化代码中的大小
objp = np.zeros((6*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2)
要使其适用于多种棋盘尺寸,您可以像这样调整代码:
# checkerboard Dimensions
cbrow = 5
cbcol = 7
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((cbrow * cbcol, 3), np.float32)
objp[:, :2] = np.mgrid[0:cbcol, 0:cbrow].T.reshape(-1, 2)
.
.
.
ret, corners = cv2.findChessboardCorners(gray, (cbcol, cbrow), None)
谢谢@s-low!您的源代码非常有用。
另一个初学者可能犯的错误是objp的数据类型。
当我分配 objp = np.zeros((6*7,3), np.float32)
时,我忽略了数据类型分配。在python 2.7中,默认的dtype
是float64
。所以,当代码调用函数'cv2.calibrateCamera
'时,出现了类似的断言错误:
OpenCV Error: Assertion failed (ni >= 0) in collectCalibrationData, file /Users/jhelmus/anaconda/conda-bld/work/opencv-2.4.8/modules/calib3d/src/calibration.cpp, line 3169
所以,只是源代码ni = objpt.checkVector(3, CV_32F)
给了我一个线索,objp的矩阵必须分配给float32
。
我遇到了同样的问题,经过一番研究后,我在此处的答案中发现了问题。
我解决了它改变 objp
:
objp = objp.reshape(-1,1,3)
我还有另一个问题:findChessboardCorners
找到的角点数可能小于 7*6(图案大小)所以我只保留找到的角点数 3D 点:
corners2 = cv2.cornerSubPix(image=gray, corners=corners,
winSize=(11,11), zeroZone=(-1,-1),
criteria=(cv2.TERM_CRITERIA_EPS +
cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001))
imgpoints.append(corners2)
objpoints.append(objp[0:corners2.shape[0]])
在那之后代码工作正常 :D
编辑:我意识到如果不使用 retval
(真或假)我们检查 corners
不是 None
。
如果您遵循以下示例:
那么,问题就很好解决了,因为函数:
Corners2 = cv2.cornerSubPix(灰色,角,(11,11),(-1,1),标准)
在当前版本的opencv中returns为空
这个也是:
img = cv2.drawChessboardCorners (img, (7.6), corners2, ret)
所以你所要做的就是更改那些代码行,这是我改编的代码:
from webcam import Webcam
import cv2
from datetime import datetime
import numpy as np
webcam = Webcam()
webcam.start()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
objp = np.zeros((6*9,3), np.float32)
objp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2)
objpoints = []
imgpoints = []
i = 0
while i < 10:
image = webcam.get_current_frame()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, (9,6), None)
print ret
if ret == True:
cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
imgpoints.append(corners)
objpoints.append(objp)
cv2.drawChessboardCorners(image, (9,6), corners,ret)
i += 1
cv2.imshow('grid', image)
cv2.waitKey(1000)
cv2.destroyAllWindows()
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
np.savez("webcam_calibration_ouput_2", ret=ret, mtx=mtx, dist=dist, rvecs=rvecs, tvecs=tvecs)
网络摄像头class:
import cv2
from threading import Thread
class Webcam:
def __init__(self):
self.video_capture = cv2.VideoCapture(0)
self.current_frame = self.video_capture.read()[1]
# create thread for capturing images
def start(self):
Thread(target=self._update_frame, args=()).start()
def _update_frame(self):
while(True):
self.current_frame = self.video_capture.read()[1]
# get the current frame
def get_current_frame(self):
return self.current_frame
请注意,数字 6 和 9 可能会根据您的国际象棋的尺寸而变化,我的国际象棋的尺寸是 10x7。
我在输入自己用手机相机拍摄的 jpg 图片时遇到了同样的问题。最初,当我只是 运行 您分享的 link 中可用的代码时,我发现 rect
总是设置为 FALSE
。后来我发现我输入的是棋盘的确切大小,这使得代码无法识别棋盘图案。我的意思是我使用了大小为 8X6
的棋盘并在代码中输入了 8X6
,例如如下所示
objp = np.zeros((6*8,3), np.float32)
objp[:,:2] = np.mgrid[0:8,0:6].T.reshape(-1,2)
因为它无法识别模式,当我将行和列维度分别减少 1(或超过一,在我的例子中,它是 7X5
)然后繁荣,我得到了打印图像作为输出的参数。
objp = np.zeros(((5*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:5].T.reshape(-1,2)
此外,如果您将此文档用于 OpenCV 3.0 beta doc there's a minor change that might need to be rectified, the difference of which you can spot by going here
我遇到了同样的问题,导致断言失败(ni > 0 && ni == ni1); 我认为应该了解第一个答案中讨论过的 ni 和 ni1 的真正含义。 objectpoints 和 imagepoints 应该是完全相同的大小。无论垫子的数量或垫子的大小。 对我来说,我的问题是我有 5 个垫子用于图像点和对象点,而对于垫子的大小,图像点为 36*2,而对象点为 48*3。所以我说它们应该完全一样,除了一个是point2f,另一个是point3f。