前言
pybind11功能强大,将C++ 程序包装为python接口,对于不太熟悉C++的同学只需要调用python接口即可,方便实用。之前的一系列pybind11文章大多数是基础的用法,本人学习pybind11的最初动机是想将一个目标跟踪程序(C++代码)封装为python接口,这样每次运行算法时候就不用打开Visaul Studio这样大型IDE(加载慢,电脑容易卡)。C++程序封装为python接口有好几种方法:boost.python, ctype(调用C++ 动态链接库), SWIG, pybind11。 我只简单用过swig, ctype。 SWIG也挺不错的,不仅可以生成python接口,还可以生成Java等其他语言接口,文档详细。
目标跟踪算法
About KCF
KCF(Kernelized Correlation Filter)目标跟踪算法是基于机器学习的,速度快,效果也比较好(抗短时遮挡)。原版的KCF代码是采用opencv, C++实现的, opencv3.2.0(contrib)之后的版本已经将KCF集成到tracking模块,但是测试发现效果不如原版的C++代码。
下面将C++ KCF 采用pybind11包装为python接口。
开发测试环境
- windows10, 64bit
- Anaconda3, with python3.7
- opencv3.4.0, with opencv_contrib
- Visual Studio 2017
- pycharm
KCF-Python
工程概述
KCF C++程序是采用类进行封装的,所有功能在:KCFTracker
类中。 因此,只需要将KCFTracker
类封装为python 接口就大功告成。
Visaul Stduio工程
python测试工程
python测试代码
import cv2
import numpy as np
import matplotlib.pyplot as plt
import demo12.kcf_demo as kcf
import time
cv2.useOptimized()
cv2.setUseOptimized(True)
cv2.setNumThreads(4)
capture = cv2.VideoCapture()
assert capture.open('D:\\ti_project\\TI_DSP_LAB\\Video-tools-exe\\video-01\\V90116-132715.mp4')
capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
frame = np.zeros(shape=[int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)),
int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)),
3], dtype=np.uint8)
for i in range(1):
capture.read(frame)
rect = cv2.selectROI('Choose object', frame, False, False)
tracker = kcf.KCFTracker(True, True, True, True)
r = [rect[0] + rect[2], rect[1] + rect[3]]
tracker.trackerInit([rect[0], rect[1], rect[0] + rect[2], rect[1] + rect[3]], frame)
count = 0
while True:
ret, frame = capture.read()
if not ret:
print('finish!')
break
t_start = time.time()
rect = tracker.trackerUpdate(frame)
t_stop = time.time()
fps = int(1.0/(t_stop - t_start))
print(rect)
cv2.rectangle(frame, (rect[0], rect[1]), (rect[2], rect[3]), (0, 255, 255), 2)
cv2.putText(frame, '#' + str(count + 1), (64, 64), 1, 1, (255, 0, 0))
cv2.putText(frame, '{}fps'.format(fps), (64, 64+30), 1, 1, (255, 0, 0))
count += 1
cv2.imshow('kcf', frame)
if cv2.waitKey(33) == 'q':
break
demo演示
选取目标
跟踪过程
完整工程实现
在上文中,实现了以下步骤
步骤
- 首先调试好目标跟踪算法,确保算法正常运行
- 包含pybind11,为目标跟踪算法编写python接口
- 采用Visual Studio生成.pyd扩展, 验证python接口的正确性
- 在python中导入.pyd,调用python接口,验证算法
但是这种直接采用Visual Studio生成.pyd的方式存在一些局限,不能很好的在其他计算机、系统、硬件平台调用,为此,直接发布源码,在相应的平台进行编译生成pyd.
工程
在python工程中,创建一个package, 一般python大多数包的名字都是pyxxxx, 因此这里取名pykcf, 在pykcf包中再新建一个package, 取名tracker
将之前Visual Studio工程中所有C++代码复制进来,并且创建一个setup.py文件
编写setup.py文件, setup.py用于设置需要生成的python扩展的配置信息.
- Extension python扩展,需要设置C++源码,C++头文件,C++链接库
- setup 编译安装python扩展
因此本工程代码中用到了以下第三方库:
- opencv
- pybind11
- numpy
因此,需要包含这些库的头文件,链接库
setup.py
from setuptools import Extension
from setuptools import setup
__version__ = '0.0.1'
ext_module = Extension(
name='kcf_demo',
sources=
[
r'main.cpp',
r'mat_warper.cpp',
r'ndarray_converter.cpp',
r'./kcf/fhog.cpp',
r'./kcf/kcftracker.cpp'
],
include_dirs=
[
r'D:/Anaconda3_2/include',
r'D:/Anaconda3_2/Lib/site-packages/numpy/core/include',
r'D:/opencv3.4.0+contrib/include',
r'D:/pybind11-master/include'
],
library_dirs=
[
r'D:/Anaconda3_2/Lib/site-packages/numpy/core/lib',
r'D:/opencv3.4.0+contrib/x64/vc15/lib'
],
libraries=
[
'opencv_aruco340',
'opencv_bgsegm340',
'opencv_bioinspired340',
'opencv_calib3d340',
'opencv_ccalib340',
'opencv_core340',
'opencv_datasets340',
'opencv_dnn340',
'opencv_dpm340',
'opencv_face340',
'opencv_features2d340',
'opencv_flann340',
'opencv_fuzzy340',
'opencv_hdf340',
'opencv_highgui340',
'opencv_imgcodecs340',
'opencv_imgproc340',
'opencv_img_hash340',
'opencv_line_descriptor340',
'opencv_ml340',
'opencv_objdetect340',
'opencv_optflow340',
'opencv_phase_unwrapping340',
'opencv_photo340',
'opencv_plot340',
'opencv_reg340',
'opencv_rgbd340',
'opencv_saliency340',
'opencv_shape340',
'opencv_stereo340',
'opencv_stitching340',
'opencv_structured_light340',
'opencv_superres340',
'opencv_surface_matching340',
'opencv_text340',
'opencv_tracking340',
'opencv_video340',
'opencv_videoio340',
'opencv_videostab340',
'opencv_xfeatures2d340',
'opencv_ximgproc340',
'opencv_xobjdetect340',
'opencv_xphoto340',
'npymath'
],
language='c++'
)
setup(
name='kcf_demo',
version=__version__,
author_email='xxxx@qq.com',
description='A simaple demo',
ext_modules=[ext_module],
install_requires=['numpy']
)
开始编译生成python扩展,激动!!!, 在pycharm中进入终端,并且进入到setup.py所在目录。
cd ./pykcf/tracker
python setup.py build_ext --inplace
python扩展生成成功!!!
演示效果
在工程中新建一个demo.py脚本,编写测试代码
run
首先选择一个跟踪目标,使用鼠标框选,然后Enter,开始跟踪。