Path: blob/master/modules/python/test/test_lk_homography.py
16337 views
#!/usr/bin/env python12'''3Lucas-Kanade homography tracker test4===============================5Uses goodFeaturesToTrack for track initialization and back-tracking for match verification6between frames. Finds homography between reference and current views.7'''89# Python 2/3 compatibility10from __future__ import print_function1112import numpy as np13import cv2 as cv1415#local modules16from tst_scene_render import TestSceneRender17from tests_common import NewOpenCVTests, isPointInRect1819lk_params = dict( winSize = (19, 19),20maxLevel = 2,21criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03))2223feature_params = dict( maxCorners = 1000,24qualityLevel = 0.01,25minDistance = 8,26blockSize = 19 )2728def checkedTrace(img0, img1, p0, back_threshold = 1.0):29p1, _st, _err = cv.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)30p0r, _st, _err = cv.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)31d = abs(p0-p0r).reshape(-1, 2).max(-1)32status = d < back_threshold33return p1, status3435class lk_homography_test(NewOpenCVTests):3637render = None38framesCounter = 039frame = frame0 = None40p0 = None41p1 = None42gray0 = gray1 = None43numFeaturesInRectOnStart = 04445def test_lk_homography(self):46self.render = TestSceneRender(self.get_sample('samples/data/graf1.png'),47self.get_sample('samples/data/box.png'), noise = 0.1, speed = 1.0)4849frame = self.render.getNextFrame()50frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)51self.frame0 = frame.copy()52self.p0 = cv.goodFeaturesToTrack(frame_gray, **feature_params)5354isForegroundHomographyFound = False5556if self.p0 is not None:57self.p1 = self.p058self.gray0 = frame_gray59self.gray1 = frame_gray60currRect = self.render.getCurrentRect()61for (x,y) in self.p0[:,0]:62if isPointInRect((x,y), currRect):63self.numFeaturesInRectOnStart += 16465while self.framesCounter < 200:66self.framesCounter += 167frame = self.render.getNextFrame()68frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)69if self.p0 is not None:70p2, trace_status = checkedTrace(self.gray1, frame_gray, self.p1)7172self.p1 = p2[trace_status].copy()73self.p0 = self.p0[trace_status].copy()74self.gray1 = frame_gray7576if len(self.p0) < 4:77self.p0 = None78continue79_H, status = cv.findHomography(self.p0, self.p1, cv.RANSAC, 5.0)8081goodPointsInRect = 082goodPointsOutsideRect = 083for (_x0, _y0), (x1, y1), good in zip(self.p0[:,0], self.p1[:,0], status[:,0]):84if good:85if isPointInRect((x1,y1), self.render.getCurrentRect()):86goodPointsInRect += 187else: goodPointsOutsideRect += 18889if goodPointsOutsideRect < goodPointsInRect:90isForegroundHomographyFound = True91self.assertGreater(float(goodPointsInRect) / (self.numFeaturesInRectOnStart + 1), 0.6)92else:93self.p0 = cv.goodFeaturesToTrack(frame_gray, **feature_params)9495self.assertEqual(isForegroundHomographyFound, True)969798if __name__ == '__main__':99NewOpenCVTests.bootstrap()100101102