利用python学习OpenCV,个人感觉比较方便。函数的形式与C++基本相同,所以切换过来还是比较好的,对于像我这种对python不太熟练的人,使用python的集成开发环境PyCharm进行学习,可以设置断点调试,有助于我这类初学者理解掌握。
下面是利用python语言结合OpenCV进行摄像机位姿估计的代码:
# -*- coding:utf-8 -*-
__author__ = 'Microcosm'
import cv2
import numpy as np
import glob
# 加载数据
with np.load('B.npz') as X:
mtx, dist, _, _ = [X[i] for i in ('mtx','dist','rvecs','tvecs')]
def draw(img,corners, imgpts):
corner = tuple(corners[0].ravel())
cv2.line(img, corner, tuple(imgpts[0].ravel()), (255,0,0), 5)
cv2.line(img, corner, tuple(imgpts[1].ravel()), (0,255,0), 5)
cv2.line(img, corner, tuple(imgpts[2].ravel()), (0,0,255), 5)
return img
def draw2(img,imgpts):
imgpts = np.int32(imgpts).reshape(-1,2)
cv2.drawContours(img, [imgpts[:4]], -1, (0,255,0),-3)
for i,j in zip(range(4),range(4,8)):
cv2.line(img,tuple(imgpts[i]),tuple(imgpts[j]),(255),3)
cv2.drawContours(img,[imgpts[4:]],-1, (0,0,255),3)
return img
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) # 坐标轴
#axis = np.float32([[0,0,0], [0,3,0],[3,3,0],[3,0,0], # 渲染立方体
# [0,0,-3],[0,3,-3],[3,3,-3],[3,0,-3]])
images = glob.glob("E:\python\Python Project\opencv_showimage\images\calibrateImages\*.jpg")
for fname in images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, (7,6), None)
if ret:
rvecs, tvecs, inliers = cv2.solvePnPRansac(objp, corners, mtx, dist)
imgpts, jac = cv2.projectPoints(axis, rvecs, tvecs, mtx, dist)
img = draw(img, corners, imgpts)
#img = draw2(img, imgpts)
cv2.imshow('img', img)
k = cv2.waitKey(0) & 0xff
if k == 's':
cv2.imwrite('res.jpg', img)
cv2.destroyAllWindows()