view python/compute-homography.py @ 185:c06379f25ab8

utilities for user types
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Fri, 25 Nov 2011 18:44:59 -0500
parents b0719b3ad3db
children ba71924cadf5
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()

dstPts, srcPts = cvutils.loadPointCorrespondences(args[0])
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()