python - Python OpenCV.remap/undistort 剪切图像
问题描述
我尝试从 OpenCV python 站点实现相机校准。这是我的代码:
import numpy as np
import cv2 as cv
import glob
CHECKERBOARD = (8,6)
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001)
objp = np.zeros((CHECKERBOARD[0]*CHECKERBOARD[1],3), np.float32) #[56][3]
# (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp[:,:2] = np.mgrid[0:CHECKERBOARD[0],0:CHECKERBOARD[1]].T.reshape(-1,2)
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.
# images like *.jpg
lastImageWithPattern = None # last image with pattern recognize
images = glob.glob('*.jpg')
for fname in images:
img = cv.imread(fname) #read image
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) #black and white
# find corners
# ret: are there corners, corners: corners coordinates
ret, corners = cv.findChessboardCorners(gray,(CHECKERBOARD[0],CHECKERBOARD[1]), None)
if ret == True:
lastImageWithPattern = fname
print("Found pattern in " + fname)
# fix corners coordinates
corners2 = cv.cornerSubPix(gray,corners, (11,11), (-1,-1), criteria)
# save corners coordinate
objpoints.append(objp)
imgpoints.append(corners)
if lastImageWithPattern is not None:
# Camera calibration
# return: is OK calib, camera matrix, distortion,rotation vector, translation vector
ret, matrix, distortion, r_vecs, t_vecs = cv.calibrateCamera( objpoints, imgpoints, gray.shape[::-1], None, None)
img = cv.imread(lastImageWithPattern)
h,w = img.shape[:2] # размерите на изображението
newCameraMatrix, roi = cv.getOptimalNewCameraMatrix(matrix, distortion, (w,h),1,(w,h))
#fix distortion
mapx, mapy = cv.initUndistortRectifyMap(matrix, distortion, None, newCameraMatrix, (w,h), 5)
dst = cv.remap(img, mapx, mapy, cv.INTER_LINEAR)
# Crop image
x,y,w,h = roi
dst = dst[y:y+h, x:x+w]
cv.imwrite('calibResult.jpg', dst)
我用了10张照片。例如,这里我将只显示一张图片。如果仅使用此图像,结果问题是相同的:
在脚本的结尾,我希望图像具有固定的失真,并且可能会丢失一些像素,但不是几乎所有的像素。在这种情况下,我的结果图像(calibResult.jpg)是:
如果我使用同一标题中的cv.undistort,结果是相同的。我想知道为什么图像如此剪切并且可能更加失真。
当我使用 samples/data/left01.jpg – left14.jpg 时,我的代码工作正常,也许我的图像中的某些内容不正常,但我不知道什么以及如何调试它。
解决方案
推荐阅读
- hashmap - 查找重复项的方法 - Kafka 和队列
- java - JTextField 和 DefaultButton 关于 ENTER 键消耗
- c++ - Intellisense 弹出数千个错误
- java - java - 如何将用户定义的数据类型中的值插入到java中的对象?
- google-sheets - 谷歌脚本对齐文本位置
- javascript - 我可以使用 messageEmbed 退货吗?
- python - 选择排序的for循环传递问题
- sql-server - 无法使用彼此的外键创建表
- python - asyncio Queue - 使用常规生成器插入项目 - 令人困惑的行为,意外的值
- server - DataTables 警告:表 id=user_data - Ajax 错误。有关此错误的更多信息,请参阅 http://datatables.net/tn/7