Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Nuzhny007 committed Aug 3, 2021
1 parent c293a57 commit 256dd2c
Show file tree
Hide file tree
Showing 199 changed files with 46,135 additions and 1 deletion.
8 changes: 8 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,14 @@ if (BUILD_YOLO_TENSORRT)
add_definitions(-DBUILD_YOLO_TENSORRT)
endif(BUILD_YOLO_TENSORRT)

option(MTRACKER_PYTHON "Build mtracking Python bindings?" ON)
if(MTRACKER_PYTHON)
set(PYBIND11_LTO_CXX_FLAGS "")
set(PYBIND11_PYTHON_VERSION 3)
add_subdirectory(thirdparty/pybind11)
endif(MTRACKER_PYTHON)


add_subdirectory(thirdparty)
add_subdirectory(src)

Expand Down
95 changes: 95 additions & 0 deletions demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import sys
import glob
import getopt
import numpy as np
import cv2 as cv
import pymtracking as mt

print("OpenCV Version: {}".format(cv.__version__))


def draw_regions(img, regions, color):
for reg in regions:
cv.rectangle(img, (reg.x(), reg.y(), reg.width(), reg.height()), color, 2)


def draw_tracks(img, tracks, fps):
for track in tracks:
if track.isStatic:
cv.rectangle(img, (track.x(), track.y(), track.width(), track.height()), (255, 0, 255), 2)
elif track.IsRobust(int(fps / 4), 0.7, 0.1, 10.):
cv.rectangle(img, (track.x(), track.y(), track.width(), track.height()), (0, 255, 0), 2)


def main():
args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
try:
video_src = video_src[0]
except:
video_src = 0
args = dict(args)
#cascade_fn = args.get('--cascade', "data/haarcascades/haarcascade_frontalface_alt.xml")
#nested_fn = args.get('--nested-cascade', "data/haarcascades/haarcascade_eye.xml")

cam = cv.VideoCapture(video_src)

_ret, img = cam.read()

fps = cam.get(cv.CAP_PROP_FPS)

configBGFG = mt.MapStringString()
configBGFG['samples'] = '20'
configBGFG["pixelNeighbor"] = "3"
configBGFG["distanceThreshold"] = "18"
configBGFG["matchingThreshold"] = "3"
configBGFG["updateFactor"] = "16"
mdetector = mt.MotionDetector(mt.MotionDetector.VIBE, img)
mdetector.Init(configBGFG)
mdetector.SetMinObjectSize(int(img.shape[0] / 100), int(img.shape[0] / 100))
print(mdetector.CanGrayProcessing())

tracker_settings = mt.TrackerSettings()

tracker_settings.SetDistance(mt.MTracker.DistRects)
tracker_settings.kalmanType = mt.MTracker.KalmanLinear
tracker_settings.filterGoal = mt.MTracker.FilterCenter
tracker_settings.lostTrackType = mt.MTracker.TrackCSRT
tracker_settings.matchType = mt.MTracker.MatchHungrian
tracker_settings.useAcceleration = False
tracker_settings.dt = 0.2
tracker_settings.accelNoiseMag = 0.2
tracker_settings.distThres = 0.95
tracker_settings.minAreaRadiusPix = -1.
tracker_settings.minAreaRadiusK = 0.8
tracker_settings.useAbandonedDetection = True
tracker_settings.minStaticTime = 3
tracker_settings.maxStaticTime = 3 * tracker_settings.minStaticTime
tracker_settings.maximumAllowedSkippedFrames = int(tracker_settings.minStaticTime * fps)
tracker_settings.maxTraceLength = 2 * tracker_settings.maximumAllowedSkippedFrames

mtracker = mt.MTracker(tracker_settings)

while True:
_ret, img = cam.read()

mdetector.Detect(img)
regions = mdetector.GetDetects()

mtracker.Update(regions, img, fps)
tracks = mtracker.GetTracks()
print("detects:", len(regions), ", tracks:", len(tracks))

vis = img.copy()
# draw_regions(vis, rects, (255, 0, 255))
draw_tracks(vis, tracks, fps)
cv.imshow('detect', vis)

if cv.waitKey(1) == 27:
break

print('Done')


if __name__ == '__main__':
main()
cv.destroyAllWindows()
156 changes: 156 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import os
import re
import sys
import platform
import subprocess
import shutil

from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from setuptools.command.install_lib import install_lib
from distutils.version import LooseVersion


class CMakeExtension(Extension):
def __init__(self, name, sourcedir=''):
Extension.__init__(self, name, sources=[])
self.sourcedir = os.path.abspath(sourcedir)


class CMakeBuild(build_ext):
def run(self):
try:
out = subprocess.check_output(['cmake', '--version'])
except OSError:
raise RuntimeError("CMake must be installed to build the following extensions: " +
", ".join(e.name for e in self.extensions))

if platform.system() == "Windows":
cmake_version = LooseVersion(re.search(r'version\s*([\d.]+)', out.decode()).group(1))
if cmake_version < '3.1.0':
raise RuntimeError("CMake >= 3.1.0 is required on Windows")

for ext in self.extensions:
self.build_extension(ext)

def build_extension(self, ext):
extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name)))
# required for auto-detection of auxiliary "native" libs
if not extdir.endswith(os.path.sep):
extdir += os.path.sep

if platform.system() == "Windows":
cmake_args = ['-DPYTHON_EXECUTABLE=' + sys.executable]
else:
cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir, '-DPYTHON_EXECUTABLE=' + sys.executable]

cfg = 'Debug' if self.debug else 'Release'
build_args = ['--config', cfg]


if platform.system() == "Windows":
cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)]
if sys.maxsize > 2**32:
cmake_args += ['-A', 'x64']
build_args += ['--', '/m']
else:
cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg]
build_args += ['--', '-j4']

cmake_args += ['-DBUILD_YOLO_LIB=OFF']
cmake_args += ['-DBUILD_YOLO_TENSORRT=OFF']

env = os.environ.copy()
env['CXXFLAGS'] = '{} -DVERSION_INFO=\\"{}\\"'.format(env.get('CXXFLAGS', ''),
self.distribution.get_version())
if not os.path.exists(self.build_temp):
os.makedirs(self.build_temp)
subprocess.check_call(['cmake', ext.sourcedir + os.path.sep + 'build'] + cmake_args, cwd='.', env=env)
subprocess.check_call(['cmake', '--build', 'build'] + build_args, cwd='.')


__metaclass__ = type
class InstallCMakeLibs(install_lib, object):
"""
Get the libraries from the parent distribution, use those as the outfiles
Skip building anything; everything is already built, forward libraries to
the installation step
"""
def run(self):
"""
Copy libraries from the bin directory and place them as appropriate
"""
self.announce("Moving library files", level=3)
# We have already built the libraries in the previous build_ext step
self.skip_build = True

if platform.system() == "Windows":
if platform.system() == "Windows":
bin_dir = os.path.join('build', 'Release')
else:
bin_dir = 'build'
print(bin_dir)
libs = [os.path.join(bin_dir, _lib) for _lib in
os.listdir(bin_dir) if
os.path.isfile(os.path.join(bin_dir, _lib)) and
os.path.splitext(_lib)[1] in [".dll", ".so"]
and not (_lib.startswith("python"))]
else:
if hasattr(self.distribution, 'bin_dir'):
bin_dir = self.distribution.bin_dir
else:
bin_dir = os.path.join(self.build_dir)

# Depending on the files that are generated from your cmake
# build chain, you may need to change the below code, such that
# your files are moved to the appropriate location when the installation
# is run
libs = [os.path.join(bin_dir, _lib) for _lib in
os.listdir(bin_dir) if
os.path.isfile(os.path.join(bin_dir, _lib)) and
os.path.splitext(_lib)[1] in [".dll", ".so"]
and not (_lib.startswith("python"))]

print('Install libs', libs, 'from', bin_dir, 'to', self.build_dir)
for lib in libs:
shutil.move(lib, os.path.join(self.build_dir, os.path.basename(lib)))
# Mark the libs for installation, adding them to
# distribution.data_files seems to ensure that setuptools' record
# writer appends them to installed-files.txt in the package's egg-info
#
# Also tried adding the libraries to the distribution.libraries list,
# but that never seemed to add them to the installed-files.txt in the
# egg-info, and the online recommendation seems to be adding libraries
# into eager_resources in the call to setup(), which I think puts them
# in data_files anyways.
#
# What is the best way?
# These are the additional installation files that should be
# included in the package, but are resultant of the cmake build
# step; depending on the files that are generated from your cmake
# build chain, you may need to modify the below code
self.distribution.data_files = [os.path.join(self.install_dir,
os.path.basename(lib))
for lib in libs]
# Must be forced to run after adding the libs to data_files
self.distribution.run_command("install_data")
super(InstallCMakeLibs, self).run()


setup(
name='pymtracking',
version='1.0.1',
author='Nuzhny007',
author_email='nuzhny@mail.ru',
url='https://github.com/Nuzhny007',
description='Multipe object tracking library',
long_description='',
ext_modules=[CMakeExtension('pymtracking')],
#cmdclass=dict(build_ext=CMakeBuild, install_lib=InstallCMakeLibs),
cmdclass={
'build_ext': CMakeBuild,
'install_lib': InstallCMakeLibs
},
zip_safe=False,
)
34 changes: 33 additions & 1 deletion src/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,34 @@
add_subdirectory(Detector)
add_subdirectory(Tracker)
add_subdirectory(Tracker)

if(MTRACKER_PYTHON)
file(GLOB_RECURSE mtracker_python_src python_bind/*.cpp)
file(GLOB_RECURSE mtracker_python_inc python_bind/*.h)

include_directories(${CMAKE_SOURCE_DIR}/thirdparty/pybind11/include)
include_directories(${PYTHON_INCLUDE_DIRS})
include_directories(${NUMPY_INCLUDE_DIR})

if (MSVC)
if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "4")
set(BIT_SYSTEM x32)
else()
set(BIT_SYSTEM x64)
endif()

include_directories(Detector/darknet/3rdparty/include)
link_directories(Detector/darknet/3rdparty/lib/${BIT_SYSTEM})
set(LIB_PTHREAD pthreadVC2)
else()
set(LIB_PTHREAD pthread)
endif()

pybind11_add_module(pymtracking ${mtracker_python_src} ${mtracker_python_inc})
target_link_libraries(pymtracking PRIVATE mtracking mdetection ${OpenCV_LIBS} ${PYTHON_LIBRARY} pybind11::module)

# set_target_properties(pymtracking PROPERTIES SUFFIX "${PYTHON_MODULE_EXTENSION}")

# target_compile_definitions(pymtracking PRIVATE BGS_PYTHON_SUPPORT=1)

set_property(TARGET pymtracking PROPERTY OUTPUT_NAME "pymtracking")
endif()
Loading

0 comments on commit 256dd2c

Please sign in to comment.