博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
12 KLT算法
阅读量:4966 次
发布时间:2019-06-12

本文共 5137 字,大约阅读时间需要 17 分钟。

1 去除多余模块的

#-*- coding:utf-8 -*-'''Lucas-Kanade tracker====================Lucas-Kanade sparse optical flow demo. Uses goodFeaturesToTrackfor track initialization and back-tracking for match verificationbetween frames.Lucas Kanade稀疏光流Demo。使用goodfeaturestotrack用于轨迹初始化和跟踪跟踪的匹配验证帧间。Usage-----lk_track.py [
]Keys----ESC - exit'''# Python 2/3 compatibilityimport numpy as npimport cv2lk_params = dict( winSize = (15, 15), maxLevel = 3, criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))feature_params = dict( maxCorners = 800, qualityLevel = 0.3, minDistance = 7, blockSize = 7 )class App: def __init__(self, video_src): self.track_len = 10 #跟踪轨迹长度10 self.detect_interval = 5 self.tracks = [] #储存跟踪点 self.cam = cv2.VideoCapture(video_src) self.frame_idx = 0 def run(self): while True: ret, frame = self.cam.read() frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) vis = frame.copy() if len(self.tracks) > 0: img0, img1 = self.prev_gray, frame_gray p0 = np.float32([tr[-1] for tr in self.tracks]).reshape(-1, 1, 2) p1, st, err = cv2.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params) p0r, st, err = cv2.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params) d = abs(p0-p0r).reshape(-1, 2).max(-1) good = d < 1 new_tracks = [] for tr, (x, y), good_flag in zip(self.tracks, p1.reshape(-1, 2), good): if not good_flag: continue tr.append((x, y)) if len(tr) > self.track_len: del tr[0] new_tracks.append(tr) cv2.circle(vis, (x, y), 2, (0, 255, 0), -1) self.tracks = new_tracks cv2.polylines(vis, [np.int32(tr) for tr in self.tracks], False, (0, 255, 0)) # draw_str(vis, (20, 20), 'track count: %d' % len(self.tracks)) if self.frame_idx % self.detect_interval == 0: mask = np.zeros_like(frame_gray) mask[:] = 255 for x, y in [np.int32(tr[-1]) for tr in self.tracks]: cv2.circle(mask, (x, y), 5, 0, -1) p = cv2.goodFeaturesToTrack(frame_gray, mask = mask, **feature_params) if p is not None: for x, y in np.float32(p).reshape(-1, 2): self.tracks.append([(x, y)]) self.frame_idx += 1 self.prev_gray = frame_gray cv2.imshow('lk_track', vis) ch = cv2.waitKey(1) if ch == 27: breakdef main(): video_src = 'traffic.flv' App(video_src).run() cv2.destroyAllWindows()if __name__ == '__main__': main()

 

2。还原成普通函数

#-*- coding:utf-8 -*-import numpy as npimport cv2#ShiTomasi 角检测的参数lk_params = dict( winSize  = (15, 15),                  maxLevel = 3,                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))# l-k 光流参数feature_params = dict( maxCorners = 800,                       qualityLevel = 0.3,                       minDistance = 7,                       blockSize = 7 )track_len = 10  # 跟踪轨迹长度10detect_interval = 5tracks = []  # 储存跟踪点frame_idx = 0# 1,定义一个对象,存储读取的视频video_src = 'traffic.flv'cam = cv2.VideoCapture(video_src)while True:    ret, frame = cam.read()    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)    vis = frame.copy()    if len(tracks) > 0:        img0, img1 = prev_gray, frame_gray        p0 = np.float32([tr[-1] for tr in tracks]).reshape(-1, 1, 2)        p1, st, err = cv2.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)        p0r, st, err = cv2.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)        d = abs(p0 - p0r).reshape(-1, 2).max(-1)        good = d < 1        new_tracks = []        for tr, (x, y), good_flag in zip(tracks, p1.reshape(-1, 2), good):            if not good_flag:                continue            tr.append((x, y))            if len(tr) > track_len:                del tr[0]            new_tracks.append(tr)            cv2.circle(vis, (x, y), 2, (0, 255, 0), -1)        tracks = new_tracks        cv2.polylines(vis, [np.int32(tr) for tr in tracks], False, (0, 255, 0))        # draw_str(vis, (20, 20), 'track count: %d' % len(self.tracks))    if frame_idx % detect_interval == 0:        mask = np.zeros_like(frame_gray)        mask[:] = 255        for x, y in [np.int32(tr[-1]) for tr in tracks]:            cv2.circle(mask, (x, y), 5, 0, -1)        p = cv2.goodFeaturesToTrack(frame_gray, mask=mask, **feature_params)        if p is not None:            for x, y in np.float32(p).reshape(-1, 2):                tracks.append([(x, y)])    frame_idx += 1    prev_gray = frame_gray    cv2.imshow('lk_track', vis)    ch = cv2.waitKey(1)    if ch == 27:        breakcv2.destroyAllWindows()cam.release()

 

3。效果图

 

 

 

4

 

5.

转载于:https://www.cnblogs.com/venicid/p/8120382.html

你可能感兴趣的文章
sigar
查看>>
iOS7自定义statusbar和navigationbar的若干问题
查看>>
[Locked] Wiggle Sort
查看>>
deque
查看>>
Setting up a Passive FTP Server in Windows Azure VM(ReplyCode: 227, Entering Passive Mode )
查看>>
Python模块调用
查看>>
委托的调用
查看>>
c#中从string数组转换到int数组
查看>>
数据模型(LP32 ILP32 LP64 LLP64 ILP64 )
查看>>
java小技巧
查看>>
POJ 3204 Ikki's Story I - Road Reconstruction
查看>>
【BZOJ】2959: 长跑(lct+缩点)(暂时弃坑)
查看>>
iOS 加载图片选择imageNamed 方法还是 imageWithContentsOfFile?
查看>>
toad for oracle中文显示乱码
查看>>
SQL中Group By的使用
查看>>
错误org/aopalliance/intercept/MethodInterceptor解决方法
查看>>
Pylint在项目中的使用
查看>>
使用nginx做反向代理和负载均衡效果图
查看>>
access remote libvirtd
查看>>
(4) Orchard 开发之 Page 的信息存在哪?
查看>>