如何在OpenCV中使用单应性矩阵对图片进行变换?

14

我有两张图片(A和B),它们之间略有扭曲,存在平移、旋转和缩放的差异(例如,这些图片)。

ORIGINAL LENA DISTORTED LENA


所以我的需求是对图像 B 应用某种变换,以补偿存在的扭曲 / 平移 / 旋转,使得两个图像具有相同的大小、方向和无平移。

我已经提取了点并找到了 Homography,如下所示。但我不知道如何使用 Homography 来转换 Mat img_B,使其看起来像 Mat img_A。有什么想法吗?

//-- Localize the object from img_1 in img_2
std::vector<Point2f> obj;
std::vector<Point2f> scene;

for (unsigned int i = 0; i < good_matches.size(); i++) {
    //-- Get the keypoints from the good matches
    obj.push_back(keypoints_object[good_matches[i].queryIdx].pt);
    scene.push_back(keypoints_scene[good_matches[i].trainIdx].pt);
}

Mat H = findHomography(obj, scene, CV_RANSAC);

祝好!

2个回答

11
你不需要使用单应性矩阵来解决这个问题,你可以计算仿射变换。然而,如果你想用单应性矩阵做其他事情,可以查看下面的代码。它是从这篇关于单应性矩阵的详细文章中复制过来的。 C++示例
// pts_src and pts_dst are vectors of points in source 
// and destination images. They are of type vector<Point2f>. 
// We need at least 4 corresponding points. 

Mat h = findHomography(pts_src, pts_dst);

// The calculated homography can be used to warp 
// the source image to destination. im_src and im_dst are
// of type Mat. Size is the size (width,height) of im_dst. 

warpPerspective(im_src, im_dst, h, size);

Python示例

'''
pts_src and pts_dst are numpy arrays of points
in source and destination images. We need at least 
4 corresponding points. 
''' 
h, status = cv2.findHomography(pts_src, pts_dst)

''' 
The calculated homography can be used to warp 
the source image to destination. Size is the 
size (width,height) of im_dst
'''

im_dst = cv2.warpPerspective(im_src, h, size)

6
你需要使用warpPerspective函数。该过程类似于this教程中介绍的仿射变换和扭曲变换。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接