我想使用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 Soft\Code\pose_estimation.py", line 13, in <module>
with np.load('B.npz') as X:
File "C:\Python27\lib\site-packages\numpy\lib\npyio.py", line 422, in load
fid = open(os_fspath(file), "rb")
IOError: [Errno 2] No such file or directory: 'B.npz'帮我克服这个问题。谢谢。
发布于 2021-04-08 14:16:58
为了生成 B.npz文件,您应该在previous section的 cv.calibrateCamera() 之后添加带有一些参数(mtx, dist, rvecs 和 tvecs) 的 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格式将多个数组保存到单个文件中。
发布于 2019-05-07 14:44:06
使用np.load(' B.npz ')作为X:在这一行中,您正在尝试加载B.npz。并且在位置specified.Make中找不到该文件,因此必须将该文件放在指定的位置。
发布于 2019-05-07 21:09:48
我也在为此而苦苦挣扎。不同的是,我使用的是另一个图像,而不是棋盘,但我有相机的内部和外部参数。我想使用openCV python在我的图像上绘制3D轴。我可以知道任何参考资料或代码吗?谢谢
https://stackoverflow.com/questions/56016521
复制相似问题