gpt4 book ai didi

python - OpenCV:undistort(对于图像)和 undistortPoints 不一致

转载 作者:行者123 更新时间:2023-12-05 03:52:31 29 4
gpt4 key购买 nike

为了测试,我生成了一个网格图像作为矩阵,并再次将网格点作为点数组:

"distorted" camera image with feature points

这表示“扭曲”的相机图像以及一些特征点。当我现在取消扭曲图像和网格点时,我得到以下结果:

image and points after individual undistortion zoom into undistorted result

(请注意,“失真”图像是直的而“未失真”图像是变形的这一事实不是重点,我只是用直测试图像测试不失真功能。)

网格图像和红色网格点现在完全错位了。我用谷歌搜索,发现有些人忘记在 undistortPoints 中指定“新相机矩阵”参数,但我没有。该文档还提到了规范化,但是当我使用单位矩阵作为相机矩阵时,我仍然遇到问题。此外,它非常适合中部区域。

为什么这不一样,我用错了东西吗?

我在 Python 中使用 cv2 (4.1.0)。下面是测试代码:


import numpy as np
import matplotlib.pyplot as plt
import cv2

w = 401
h = 301


# helpers
#--------

def plotImageAndPoints(im, pu, pv):
plt.imshow(im, cmap="gray")
plt.scatter(pu, pv, c="red", s=16)
plt.xlim(0, w)
plt.ylim(0, h)
plt.show()

def cv2_undistortPoints(uSrc, vSrc, cameraMatrix, distCoeffs):
uvSrc = np.array([np.matrix([uSrc, vSrc]).transpose()], dtype="float32")
uvDst = cv2.undistortPoints(uvSrc, cameraMatrix, distCoeffs, None, cameraMatrix)
uDst = [uv[0] for uv in uvDst[0]]
vDst = [uv[1] for uv in uvDst[0]]
return uDst, vDst


# test data
#----------

# generate grid image
img = np.ones((h, w), dtype = "float32")
img[0::20, :] = 0
img[:, 0::20] = 0

# generate grid points
uPoints, vPoints = np.meshgrid(range(0, w, 20), range(0, h, 20), indexing='xy')
uPoints = uPoints.flatten()
vPoints = vPoints.flatten()

# see if points align with the image
plotImageAndPoints(img, uPoints, vPoints) # perfect!


# undistort both image and points individually
#---------------------------------------------

# camera matrix parameters
fx = 1
fy = 1
cx = w/2
cy = h/2

# distortion parameters
k1 = 0.00003
k2 = 0
p1 = 0
p2 = 0

# convert for opencv
mtx = np.matrix([
[fx, 0, cx],
[ 0, fy, cy],
[ 0, 0, 1]
], dtype = "float32")

dist = np.array([k1, k2, p1, p2], dtype = "float32")

# undistort image
imgUndist = cv2.undistort(img, mtx, dist)
# undistort points
uPointsUndist, vPointsUndist = cv2_undistortPoints(uPoints, vPoints, mtx, dist)

# test if they still match
plotImageAndPoints(imgUndist, uPointsUndist, vPointsUndist) # awful!

感谢任何帮助!

最佳答案

聚会有点晚了,但为了帮助其他人遇到这个问题:问题在于 UndistortPoints 是一种迭代计算,在某些情况下,它会在达到稳定解之前退出。这可以通过修改计算的终止条件来解决,这可以通过使用 UndistortPointsIter 来完成。你应该替换:

uvDst = cv2.undistortPoints(uvSrc, cameraMatrix, distCoeffs, None, cameraMatrix)

with:

uvDst = cv2.undistortPointsIter(uvSrc, cameraMatrix, distCoeffs, None, cameraMatrix,(cv2.TERM_CRITERIA_COUNT | cv2.TERM_CRITERIA_EPS, 40, 0.03))

现在,它会尝试 40 次迭代来找到解决方案,而不是默认的 5 次迭代。

关于python - OpenCV:undistort(对于图像)和 undistortPoints 不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62170402/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com