HOW TO use Homography to transform pictures in OpenCV?
Asked Answered
A

2

14

I've two pictures (A and B) slightly distorted one from the other, where there are translation, rotation and scale differences between them (for example, these pictures:)

ORIGINAL LENA DISTORTED LENA


Ssoooooooo what I need is to apply a kind of transformation in pic B so it compensates the distortion/translation/rotation that exists to make both pictures with the same size, orientation and with no translation

I've already extracted the points and found the Homography, as shown bellow. But I don'know how to use the Homography to transform Mat img_B so it looks like Mat img_A. Any idea?

//-- 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);

Cheers,

Asphyxiate answered 26/11, 2012 at 17:36 Comment(0)
D
6

You want the warpPerspective function. The process is analogous to the one presented in this tutorial (for affine transforms and warps)

Dodona answered 26/11, 2012 at 17:55 Comment(0)
L
11

You do not need homography for this problem. You can compute an affine transform instead. However, if you do want to use homography for other purposes, you can check out the code below. It was copied from this much detailed article on homography.

C++ Example

// 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 Example

'''
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)
Lentil answered 13/1, 2016 at 18:59 Comment(0)
D
6

You want the warpPerspective function. The process is analogous to the one presented in this tutorial (for affine transforms and warps)

Dodona answered 26/11, 2012 at 17:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.