python - 没有这样的文件或目录:在编译“pose_estimation.py”以使用 Opencv 绘制 3d 立方体时出现“B.npz”
问题描述
我想使用 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'
帮助我克服这个问题。谢谢你。
解决方案
为了生成B.npz
文件,您应该在上一节np.savez()
之后添加一些参数(mtx
、和)dist
,如下所示:rvecs
tvecs
cv.calibrateCamera()
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
将几个数组以未压缩格式保存到一个文件中。
推荐阅读
- css - 我如何将 CSS 应用于 VAADIN 8 中的组件
- javascript - 按类名保存/加载复选框状态
- java - Android Studio - 尝试使用位于自定义 xml 文件中的代码更改 TextView 属性时应用程序崩溃
- javascript - Lodash.get 等价于 Ramda
- javascript - Styled Components - 基于 props 有条件地渲染整个 css 块
- animation - 简化不适用于 svg.js v3 Rotate 的函数
- c# - 具有泛型参数的 C# 8.0 可空引用类型功能
- amazon-web-services - 以 Google Cloud 域名为例(如 EC2)
- python - “元组”对象不可调用
- python - 无法识别字符串中的字符 - Python