view python/compute-homography.py @ 151:4af774bb186d

wrote a simple script to compute homography from point correspondences and display the reprojection for visual verification
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Tue, 06 Sep 2011 17:55:06 -0400
parents
children b0719b3ad3db
line wrap: on
line source

#! /usr/bin/env python

import sys,getopt

import numpy as np
import cv2

import cvutils
import utils

options, args = getopt.getopt(sys.argv[1:], 'h',['help','video_frame='])
options = dict(options)

if '--help' in options.keys() or '-h' in options.keys():
    print('''The argument should be the name of a file containing at least 4 non-colinear point coordinates:
 - the first two lines are the x and y coordinates in the projected space (usually world space)
 - the last two lines are the x and y coordinates in the origin space (usually image space)''')
    sys.exit()

if len(args) == 0:
    print('Usage: {0} --help|-h [--video_frame <video frame filename>] [<point_correspondences.txt>]'.format(sys.argv[0]))
    sys.exit()

points = np.loadtxt(args[0], dtype=np.float32)
srcPts = points[2:,:].T
dstPts = points[:2,:].T
homography, mask = cv2.findHomography(srcPts, dstPts) # method=0, ransacReprojThreshold=3
np.savetxt(utils.removeExtension(sys.argv[1])+'-homography.txt',homography)

if '--video_frame' in options.keys() and homography.size>0:
    img = cv2.imread(options['--video_frame'])
    for p in srcPts:
        cv2.circle(img,tuple(p),2,cvutils.cvRed)
    invHomography = np.linalg.inv(homography)
    projectedDstPts = cvutils.projectArray(invHomography, dstPts.T).T
    for i,p in enumerate(projectedDstPts):
        cv2.circle(img,tuple(np.int32(np.round(p))),2,cvutils.cvBlue)
        print('img: {0} / projected: {1}'.format(srcPts[i], p))
    cv2.imshow('video frame',img)
    cv2.waitKey()