没有这样的文件或目录:'B.npz'编译'pose_estimation.py'以使用 Opencv 绘制 3d 立方体



我想使用 Opencv 和 python 在棋盘的第一个角上绘制 3D 坐标轴(X、Y、Z 轴)。

但是当我运行以下代码时,

import cv2
import numpy as np
import glob
def draw(img, corners, imgpts):
corner = tuple(corners[0].ravel())
img = cv2.line(img, corner, tuple(imgpts[0].ravel()), (255,0,0), 5)
img = cv2.line(img, corner, tuple(imgpts[1].ravel()), (0,255,0), 5)
img = cv2.line(img, corner, tuple(imgpts[2].ravel()), (0,0,255), 5)
return img
# Load previously saved data
with np.load('B.npz') as X:
mtx, dist, _, _ = [X[i] for i in ('mtx','dist','rvecs','tvecs')]
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
objp = np.zeros((6*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2)
axis = np.float32([[3,0,0], [0,3,0], [0,0,-3]]).reshape(-1,3)
for fname in glob.glob('left*.jpg'):
img = cv2.imread(fname)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, (7,6),None)
if ret == True:
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
# Find the rotation and translation vectors.
rvecs, tvecs, inliers = cv2.solvePnPRansac(objp, corners2, mtx, dist)
# project 3D points to image plane
imgpts, jac = cv2.projectPoints(axis, rvecs, tvecs, mtx, dist)
img = draw(img,corners2,imgpts)
cv2.imshow('img',img)
k = cv2.waitKey(0) & 0xff
if k == 's':
cv2.imwrite(fname[:6]+'.png', img)
cv2.destroyAllWindows()

我收到此错误:

Traceback (most recent call last):
File "D:3D Image Processing Dev SoftCodepose_estimation.py", line 13, in <module>
with np.load('B.npz') as X:
File "C:Python27libsite-packagesnumpylibnpyio.py", line 422, in load
fid = open(os_fspath(file), "rb")
IOError: [Errno 2] No such file or directory: 'B.npz'

帮助我克服这个问题。谢谢。

为了生成B.npz文件,你应该在上一节cv.calibrateCamera()后添加带有一些参数(mtxdistrvecstvecs)的np.savez(),如下所示:

for fname in images:
img = cv.imread(fname)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# Find the chess board corners
ret, corners = cv.findChessboardCorners(gray, (7,6), None)
# If found, add object points, image points (after refining them)
if ret == True:
objpoints.append(objp)
corners2 = cv.cornerSubPix(gray,corners, (11,11), (-1,-1), criteria)
imgpoints.append(corners)
# Draw and display the corners
cv.drawChessboardCorners(img, (7,6), corners2, ret)
cv.imshow('img', img)
cv.waitKey(500)
ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
np.savez('B.npz', mtx=mtx, dist=dist, rvecs=rvecs, tvecs=tvecs)
cv.destroyAllWindows()

顺便说一下,np.savez 将多个数组以未压缩的.npz格式保存到单个文件中。

,np.load('B.npz') 为 X:在这一行中,您正在尝试加载 B.npz。而它;无法在指定的位置找到该文件。确保将 fie 放置在指定位置。

我也在为此苦苦挣扎。不同之处在于,我使用的是另一个图像,而不是棋盘,但我有相机内在和外在参数。我想使用 openCV python 在我的图像上绘制 3D 轴。我可以知道任何参考或代码吗?谢谢

您必须使用 NumPy(np.savez、np.savetxt 等)保存上一个项目(https://docs.opencv.org/4.3.0/dc/dbb/tutorial_py_calibration.html)的相机矩阵和失真系数。