首页 > 解决方案 > 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 时,我的代码工作正常,也许我的图像中的某些内容不正常,但我不知道什么以及如何调试它。

标签: pythonopencvcamera-calibration

解决方案


推荐阅读