opencv 使用Python中的对应点消除图像失真

amrnrhlw  于 2023-10-24  发布在  Python
关注(0)|答案(1)|浏览(135)

我有一张图像,上面有一些特定的矩形,我想消除这些矩形的失真,这样我就可以用像素距离来估计真实世界的距离。
我开始使用我在网上找到的代码,但结果图像似乎不匹配。正常:

无失真图像:

其中蓝色矩形总是正常的,绿色是不失真的。我还尝试使用initUndistortRectifyMapinitInverseRectificationMap函数来重新Map图像和点,取得了更大的成功,但一个矩形仍然以一种奇怪的方式被Map:

代码

概述:

img = cv2.imread(str(image))
IMG_SIZE = img.shape[:-1]  # h, w
optimal_camera_matrix, roi = cv2.getOptimalNewCameraMatrix(camera_matrix, dist_coeffs, IMG_SIZE[::-1], 1, IMG_SIZE[::-1])
maps = cv2.initUndistortRectifyMap(
        camera_matrix,
        dist_coeffs,
        None,
        optimal_camera_matrix,
        IMG_SIZE[::-1],
        cv2.CV_32FC1,
    )
inv_maps = cv2.initInverseRectificationMap(
        camera_matrix,
        dist_coeffs,
        None,
        optimal_camera_matrix,
        IMG_SIZE[::-1],
        cv2.CV_32FC1,
    )

第一版:

undistorted_image = cv2.undistort(img, camera_matrix, dist_coeffs)
undistorted_begin = cv2.undistortPoints(begin, camera_matrix, dist_coeffs, None, optimal_camera_matrix).squeeze()
undistorted_end = cv2.undistortPoints(end, camera_matrix, dist_coeffs, None, optimal_camera_matrix).squeeze()

第二版:

undistorted_image = cv2.undistort(img, camera_matrix, dist_coeffs, None, optimal_camera_matrix)
undistorted_image = cv2.remap(img, maps[0], maps[1], cv2.INTER_LINEAR)
undistorted_begin = cv2.undistortPoints(begin, camera_matrix, dist_coeffs, None, optimal_camera_matrix).squeeze()
undistorted_end = cv2.undistortPoints(end, camera_matrix, dist_coeffs, None, optimal_camera_matrix).squeeze()
a8jjtwal

a8jjtwal1#

undistort points image show
它似乎在我的opencv cpp代码工作。你能给我你的数据和参数吗?我会尝试它。

int test_remap() {
std::string src_path = "./calib_data/left05.jpg";
cv::Mat intrinsic = LoadParams("./workspace/intrinsic.yaml").front();
cv::Mat distortion_coeff = LoadParams("./workspace/distortion_coeff.yaml").front();

cv::Mat test_img = cv::imread(src_path);
cv::Mat undistort_img;
cv::Mat map_x, map_y;
cv::Mat intrinsic_copy = intrinsic.clone();
cv::initUndistortRectifyMap(intrinsic, distortion_coeff, cv::Mat(), 
        intrinsic_copy, test_img.size(), CV_32FC1, map_x, map_y);
cv::remap(test_img, undistort_img, map_x, map_y, cv::InterpolationFlags::INTER_LINEAR,
        cv::BorderTypes::BORDER_CONSTANT, 0);

std::vector<cv::Point2f> undistort_pts, to_un{cv::Point2f(241., 97.)};
cv::undistortPoints(to_un, undistort_pts, intrinsic, distortion_coeff, cv::Mat(), intrinsic);
std::cout << std::endl;
std::cout << "undistort_pts " <<  undistort_pts.front() << std::endl;

cv::circle(test_img, to_un.front(), 3, cv::Scalar(0,0,255));
cv::circle(undistort_img, undistort_pts.front(), 3, cv::Scalar(0,255,0));

cv::Mat concat_img;
cv::hconcat(std::vector<cv::Mat>{test_img, undistort_img}, concat_img);
cv::imshow("undistort", concat_img);
cv::waitKey(0);}

相关问题