├── _env.lua ├── demo ├── data │ ├── lena.jpg │ ├── stitch │ │ ├── s1.jpg │ │ ├── s2.jpg │ │ ├── s3.jpg │ │ ├── s4.jpg │ │ └── s5.jpg │ ├── basketball1.png │ ├── basketball2.png │ ├── circles_pattern.png │ ├── trackbar │ │ ├── LinuxLogo.png │ │ └── WindowsLogo.png │ ├── inpainting │ │ └── lena_mask.jpg │ └── calibrateCamera │ │ ├── image.jpg │ │ ├── template1.jpg │ │ ├── template2.jpg │ │ ├── template3.jpg │ │ ├── template4.jpg │ │ ├── template5.jpg │ │ ├── template6.jpg │ │ └── template7.jpg ├── imshow.lua ├── denoising.lua ├── structs.lua ├── LineSegmentDetector.lua ├── stitch.lua ├── superres.lua ├── inpainting.lua ├── cuda │ ├── min.lua │ ├── convolution.lua │ ├── resize.lua │ └── optical_flow.lua ├── findContours.lua ├── videocap.lua ├── trackbar.lua ├── flann.lua ├── keypoints.lua ├── filtering.lua ├── SVM.lua └── calibrateCamera.lua ├── .gitignore ├── cv ├── ml │ └── CMakeLists.txt ├── core │ ├── CMakeLists.txt │ └── init.lua ├── flann │ └── CMakeLists.txt ├── highgui │ ├── CMakeLists.txt │ └── init.lua ├── imgproc │ └── CMakeLists.txt ├── optflow │ └── CMakeLists.txt ├── photo │ └── CMakeLists.txt ├── video │ └── CMakeLists.txt ├── videoio │ ├── CMakeLists.txt │ └── init.lua ├── calib3d │ └── CMakeLists.txt ├── cudacodec │ ├── CMakeLists.txt │ └── init.lua ├── imgcodecs │ ├── CMakeLists.txt │ └── init.lua ├── objdetect │ └── CMakeLists.txt ├── superres │ └── CMakeLists.txt ├── xphoto │ ├── CMakeLists.txt │ └── init.lua ├── cudaarithm │ └── CMakeLists.txt ├── cudabgsegm │ └── CMakeLists.txt ├── cudafilters │ └── CMakeLists.txt ├── cudaimgproc │ └── CMakeLists.txt ├── cudaoptflow │ └── CMakeLists.txt ├── cudastereo │ └── CMakeLists.txt ├── cudawarping │ └── CMakeLists.txt ├── features2d │ └── CMakeLists.txt ├── stitching │ └── CMakeLists.txt ├── ximgproc │ └── CMakeLists.txt ├── cudafeatures2d │ └── CMakeLists.txt ├── cudaobjdetect │ └── CMakeLists.txt ├── _env_cuda.lua └── Classes.lua ├── include ├── core.hpp ├── imgcodecs.hpp ├── xphoto.hpp ├── highgui.hpp ├── cudacodec.hpp ├── cudawarping.hpp ├── optflow.hpp ├── videoio.hpp ├── cudafilters.hpp ├── Classes.hpp ├── cudaarithm.hpp ├── CUDACommon.hpp ├── cudaobjdetect.hpp ├── cudaimgproc.hpp ├── objdetect.hpp ├── cudastereo.hpp ├── flann.hpp ├── cudabgsegm.hpp ├── ximgproc.hpp └── cudafeatures2d.hpp ├── src ├── tests │ └── TestConversion.cpp ├── core.cpp ├── imgcodecs.cpp ├── xphoto.cpp ├── Classes.cpp ├── cudacodec.cpp ├── highgui.cpp ├── videoio.cpp ├── optflow.cpp ├── flann.cpp ├── cudafilters.cpp ├── ximgproc.cpp ├── cudastereo.cpp ├── cudawarping.cpp └── cudabgsegm.cpp ├── README.md ├── cv-scm-1.rockspec ├── LICENSE ├── tests ├── conversion.lua └── test.lua ├── .travis.yml └── CMakeLists.txt /_env.lua: -------------------------------------------------------------------------------- 1 | local cv = {} 2 | 3 | return cv 4 | -------------------------------------------------------------------------------- /demo/data/lena.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/lena.jpg -------------------------------------------------------------------------------- /demo/data/stitch/s1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/stitch/s1.jpg -------------------------------------------------------------------------------- /demo/data/stitch/s2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/stitch/s2.jpg -------------------------------------------------------------------------------- /demo/data/stitch/s3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/stitch/s3.jpg -------------------------------------------------------------------------------- /demo/data/stitch/s4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/stitch/s4.jpg -------------------------------------------------------------------------------- /demo/data/stitch/s5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/stitch/s5.jpg -------------------------------------------------------------------------------- /demo/data/basketball1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/basketball1.png -------------------------------------------------------------------------------- /demo/data/basketball2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/basketball2.png -------------------------------------------------------------------------------- /demo/data/circles_pattern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/circles_pattern.png -------------------------------------------------------------------------------- /demo/data/trackbar/LinuxLogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/trackbar/LinuxLogo.png -------------------------------------------------------------------------------- /demo/data/inpainting/lena_mask.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/inpainting/lena_mask.jpg -------------------------------------------------------------------------------- /demo/data/trackbar/WindowsLogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/trackbar/WindowsLogo.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.idea 2 | *.so 3 | *~ 4 | scripts/ 5 | *.dylib 6 | build/ 7 | lib/ 8 | Makefile 9 | result.png 10 | *.rock 11 | -------------------------------------------------------------------------------- /demo/data/calibrateCamera/image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/calibrateCamera/image.jpg -------------------------------------------------------------------------------- /demo/data/calibrateCamera/template1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/calibrateCamera/template1.jpg -------------------------------------------------------------------------------- /demo/data/calibrateCamera/template2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/calibrateCamera/template2.jpg -------------------------------------------------------------------------------- /demo/data/calibrateCamera/template3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/calibrateCamera/template3.jpg -------------------------------------------------------------------------------- /demo/data/calibrateCamera/template4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/calibrateCamera/template4.jpg -------------------------------------------------------------------------------- /demo/data/calibrateCamera/template5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/calibrateCamera/template5.jpg -------------------------------------------------------------------------------- /demo/data/calibrateCamera/template6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/calibrateCamera/template6.jpg -------------------------------------------------------------------------------- /demo/data/calibrateCamera/template7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VisionLabs/torch-opencv/HEAD/demo/data/calibrateCamera/template7.jpg -------------------------------------------------------------------------------- /cv/ml/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/ml "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/core/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/core "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/flann/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/flann "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/highgui/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/highgui "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/imgproc/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/imgproc "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/optflow/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/optflow "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/photo/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/photo "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/video/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/video "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/videoio/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/videoio "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/calib3d/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/calib3d "${src}" "${luasrc}") 6 | -------------------------------------------------------------------------------- /cv/cudacodec/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/cudacodec "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/imgcodecs/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/imgcodecs "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/objdetect/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/objdetect "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/superres/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/superres "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/xphoto/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/xphoto "${src}" "${luasrc}") 6 | -------------------------------------------------------------------------------- /cv/cudaarithm/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/cudaarithm "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/cudabgsegm/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/cudabgsegm "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/cudafilters/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/cudafilters "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/cudaimgproc/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/cudaimgproc "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/cudaoptflow/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/cudaoptflow "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/cudastereo/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/cudastereo "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/cudawarping/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/cudawarping "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/features2d/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/features2d "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/stitching/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/stitching "${src}" "${luasrc}") 6 | -------------------------------------------------------------------------------- /cv/ximgproc/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/ximgproc "${src}" "${luasrc}") 6 | -------------------------------------------------------------------------------- /cv/cudafeatures2d/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/cudafeatures2d "${src}" "${luasrc}") -------------------------------------------------------------------------------- /cv/cudaobjdetect/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 2 | CMAKE_POLICY(VERSION 2.8) 3 | SET(src) 4 | FILE(GLOB luasrc *.lua) 5 | ADD_TORCH_PACKAGE(cv/cudaobjdetect "${src}" "${luasrc}") -------------------------------------------------------------------------------- /include/core.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | extern "C" { 5 | 6 | int getNumThreads(); 7 | 8 | void setNumThreads(int nthreads); 9 | 10 | struct TensorWrapper copyMakeBorder(struct TensorWrapper src, struct TensorWrapper dst, int top, 11 | int bottom, int left, int right, int borderType, 12 | struct ScalarWrapper value); 13 | } -------------------------------------------------------------------------------- /demo/imshow.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv' 2 | require 'cv.imgcodecs' 3 | require 'cv.highgui' 4 | 5 | if not arg[1] then 6 | print('Usage: `th demo/imshow.lua path-to-image`') 7 | print('Now using demo/data/lena.jpg') 8 | end 9 | 10 | local path = arg[1] or 'demo/data/lena.jpg' 11 | local im = cv.imread {path, cv.IMREAD_GRAYSCALE} 12 | 13 | if im:nElement() == 0 then 14 | error('Couldn\'t load ' .. path) 15 | end 16 | 17 | cv.imshow {"Hello, Lua!", im} 18 | cv.waitKey {0} 19 | -------------------------------------------------------------------------------- /demo/denoising.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv' 2 | require 'cv.photo' 3 | require 'cv.imgcodecs' 4 | require 'cv.highgui' 5 | 6 | if not arg[1] then 7 | print('Usage: `th demo/denoising.lua path-to-image`') 8 | print('Now using demo/data/lena.jpg') 9 | end 10 | 11 | local path = arg[1] or 'demo/data/lena.jpg' 12 | local image = cv.imread{path} 13 | 14 | if image:nDimension() == 0 then 15 | error('Couldn\'t load ' .. path) 16 | end 17 | 18 | cv.imshow{"Denoised image", cv.fastNlMeansDenoising{image}} 19 | cv.waitKey{0} 20 | -------------------------------------------------------------------------------- /demo/structs.lua: -------------------------------------------------------------------------------- 1 | -- A demo of how to use complex structs 2 | local cv = require 'cv' 3 | require 'cv.imgproc' 4 | 5 | -- RotatedRect 6 | local rect = cv.RotatedRect{center={50, 120}, size={40, 90}, angle=30} 7 | local points = cv.boxPoints{rect} 8 | print(points) 9 | 10 | -- Hu moments 11 | local points = torch.FloatTensor { 12 | {10, 23.4}, 13 | {17, 10.1}, 14 | {20, 31.2}, 15 | {65, 43.1}, 16 | {5.67, 11}, 17 | {10, 4.42} 18 | } 19 | 20 | local moments = cv.moments{points} 21 | 22 | print(cv.HuMoments{moments}) 23 | -------------------------------------------------------------------------------- /src/tests/TestConversion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | extern "C" { 4 | #include 5 | } 6 | 7 | extern "C" 8 | TensorWrapper test_mat_to_tensor() { 9 | cv::Mat outputMat = cv::Mat::ones(3, 3, CV_8SC1) * 7.; 10 | std::cout << "Sending Mat to Torch" << std::endl; 11 | return TensorWrapper(outputMat); 12 | } 13 | 14 | extern "C" 15 | void test_tensor_to_mat(TensorWrapper tensor) { 16 | cv::Mat temp = tensor; 17 | std::cout << "This is a " << temp.channels() << 18 | "-channel Mat of type " << typeStr(temp) << std::endl; 19 | std::cout << temp * 10. << std::endl; 20 | } -------------------------------------------------------------------------------- /include/imgcodecs.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | extern "C" 5 | struct TensorWrapper imread(const char *filename, int flags); 6 | 7 | extern "C" 8 | struct TensorArrayPlusBool imreadmulti(const char *filename, int flags); 9 | 10 | extern "C" 11 | bool imwrite(const char *filename, struct TensorWrapper img, struct TensorWrapper params); 12 | 13 | extern "C" 14 | struct TensorWrapper imdecode(struct TensorWrapper buf, int flags); 15 | 16 | extern "C" 17 | struct TensorWrapper imencode( 18 | const char *ext, struct TensorWrapper img, struct TensorWrapper params); -------------------------------------------------------------------------------- /demo/LineSegmentDetector.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv' 2 | require 'cv.highgui' 3 | require 'cv.imgproc' 4 | require 'cv.imgcodecs' 5 | 6 | if not arg[1] then 7 | print('Usage: `th demo/LineSegmentDetector.lua path-to-image`') 8 | print('Now using demo/data/lena.jpg') 9 | end 10 | 11 | local path = arg[1] or 'demo/data/lena.jpg' 12 | local image = cv.imread{path, cv.IMREAD_GRAYSCALE} 13 | 14 | if image:nDimension() == 0 then 15 | error('Couldn\'t load ' .. path) 16 | end 17 | 18 | local detector = cv.LineSegmentDetector{} 19 | local lines = detector:detect{image} 20 | image = detector:drawSegments{image, lines} 21 | 22 | cv.imshow{"Detected lines", image} 23 | cv.waitKey{0} 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | OpenCV bindings for LuaJIT+Torch 2 | ===================== 3 | [![Build Status](https://travis-ci.org/VisionLabs/torch-opencv.svg?branch=master)](https://travis-ci.org/VisionLabs/torch-opencv) 4 | 5 | Installation: 6 | 7 | ```shell 8 | luarocks install cv 9 | ``` 10 | 11 | For complete info on the project, including tutorials and contribution guidelines, visit its [Wiki](https://github.com/VisionLabs/torch-opencv/wiki). 12 | 13 | See [this page](https://github.com/VisionLabs/torch-opencv/wiki/Installation) for a quickstart. 14 | 15 | **Should you find a bug, please get in touch and raise an [issue](https://github.com/VisionLabs/torch-opencv/issues) so that we can help resolve it!** 16 | -------------------------------------------------------------------------------- /src/core.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | extern "C" { 5 | 6 | int getNumThreads() 7 | { 8 | return cv::getNumThreads(); 9 | } 10 | 11 | void setNumThreads(int nthreads) 12 | { 13 | cv::setNumThreads(nthreads); 14 | } 15 | 16 | struct TensorWrapper copyMakeBorder(struct TensorWrapper src, struct TensorWrapper dst, int top, 17 | int bottom, int left, int right, int borderType, 18 | struct ScalarWrapper value) 19 | { 20 | MatT dstMat = dst.toMatT(); 21 | cv::copyMakeBorder(src.toMat(), dstMat, top, bottom, left, right, borderType, value); 22 | return TensorWrapper(dstMat); 23 | } 24 | 25 | } // extern "C" -------------------------------------------------------------------------------- /cv-scm-1.rockspec: -------------------------------------------------------------------------------- 1 | package = "cv" 2 | version = "scm-1" 3 | 4 | source = { 5 | url = "git://github.com/VisionLabs/torch-opencv", 6 | tag = "master" 7 | } 8 | 9 | description = { 10 | summary = "OpenCV bindings for LuaJIT+Torch", 11 | detailed = [[ 12 | OpenCV bindings for LuaJIT+Torch 13 | ]], 14 | homepage = "https://github.com/VisionLabs/torch-opencv", 15 | license = "MIT" 16 | } 17 | 18 | dependencies = { 19 | "torch >= 7.0" 20 | } 21 | 22 | build = { 23 | type = "command", 24 | build_command = [[ 25 | cmake -E make_directory build; 26 | cd build; 27 | cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="$(LUA_BINDIR)/.." -DCMAKE_INSTALL_PREFIX="$(PREFIX)"; 28 | $(MAKE) -j5 29 | ]], 30 | install_command = "cd build && $(MAKE) install -j5" 31 | } 32 | -------------------------------------------------------------------------------- /include/xphoto.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | extern "C" 6 | struct TensorWrapper xphoto_autowbGrayworld( 7 | struct TensorWrapper src, struct TensorWrapper dst, float thresh); 8 | 9 | extern "C" 10 | struct TensorWrapper xphoto_balanceWhite( 11 | struct TensorWrapper src, struct TensorWrapper dst, int algorithmType, 12 | float inputMin, float inputMax, float outputMin, float outputMax); 13 | 14 | extern "C" 15 | struct TensorWrapper xphoto_dctDenoising( 16 | struct TensorWrapper src, struct TensorWrapper dst, double sigma, int psize); 17 | 18 | extern "C" 19 | struct TensorWrapper xphoto_inpaint( 20 | struct TensorWrapper src, struct TensorWrapper mask, 21 | struct TensorWrapper dst, int algorithmType); -------------------------------------------------------------------------------- /demo/stitch.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv' 2 | require 'cv.highgui' 3 | require 'cv.imgcodecs' 4 | require 'cv.stitching' 5 | 6 | cv.namedWindow{'Display'} 7 | 8 | local images = {} 9 | for i = 1,5 do 10 | local pathToImage = ('demo/data/stitch/s%d.jpg'):format(i) 11 | images[i] = cv.imread{pathToImage} 12 | if images[i]:nElement() == 0 then 13 | error('Couldn\'t load ' .. pathToImage) 14 | end 15 | 16 | cv.imshow{'Display', images[i]} 17 | cv.waitKey{0} 18 | end 19 | 20 | local stitcher = cv.Stitcher{} 21 | 22 | local timer = torch.Timer() 23 | local status, pano = stitcher:stitch{images} 24 | print('Processing time: ' .. timer:time().real .. ' seconds') 25 | 26 | cv.setWindowTitle{'Display', 'Panorama'} 27 | if status == 0 then 28 | cv.imshow{'Display', pano} 29 | cv.waitKey{0} 30 | else 31 | error('Stitching fail') 32 | end 33 | -------------------------------------------------------------------------------- /demo/superres.lua: -------------------------------------------------------------------------------- 1 | -- A demo of scaling images by 2 from camera on CPU 2 | -- Just to check sresolution works 3 | 4 | local cv = require 'cv' 5 | cv.superres = require 'cv.superres' 6 | require 'cv.videoio' 7 | require 'cv.highgui' 8 | 9 | local sres = cv.superres.createSuperResolution_BTVL1{} 10 | 11 | local camera = cv.superres.createFrameSource_Camera{0} 12 | sres:setInput{camera} 13 | 14 | local optFlow = cv.superres.createOptFlow_Farneback{} 15 | sres:setOpticalFlow{optFlow} 16 | 17 | -- These parameters are NOT realistic 18 | -- They're here just to show the example runs 19 | sres:setScale{2} 20 | sres:setIterations{1} 21 | sres:setTemporalAreaRadius{1} 22 | 23 | -- skip the first frame 24 | camera:nextFrame{} 25 | 26 | cv.namedWindow{"Big frame", cv.WINDOW_AUTOSIZE} 27 | local frame = sres:nextFrame{} 28 | 29 | while true do 30 | cv.imshow{"Big frame", frame} 31 | if cv.waitKey{30} >= 0 then break end 32 | 33 | sres:nextFrame{frame} 34 | end 35 | -------------------------------------------------------------------------------- /demo/inpainting.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv' 2 | require 'cv.photo' 3 | require 'cv.imgcodecs' 4 | require 'cv.highgui' 5 | require 'cv.imgproc' 6 | 7 | if not arg[1] or not arg[2] then 8 | print('Usage: `th demo/inpainting.lua path_to_image path_to_mask`') 9 | print('Now using `demo/data/lena.jpg demo/data/inpainting/lena_mask.jpg') 10 | end 11 | 12 | local image = cv.imread{arg[1] or 'demo/data/lena.jpg', cv.IMREAD_COLOR} 13 | local mask = cv.imread{arg[2] or 'demo/data/inpainting/lena_mask.jpg', cv.IMREAD_GRAYSCALE} 14 | 15 | if image:nDimension() == 0 or mask:nDimension() == 0 then 16 | error('Couldn\'t load image or mask') 17 | end 18 | 19 | cv.namedWindow{"Display"} 20 | cv.setWindowTitle{"Display", "Image + mask"} 21 | cv.imshow{"Display", cv.addWeighted{image, 0.5, cv.cvtColor{mask, nil, cv.COLOR_GRAY2BGR}, 0.5, 0}} 22 | cv.waitKey{0} 23 | 24 | local result = cv.inpaint{image, mask, dst=nil, inpaintRadius=1, flags=cv.INPAINT_TELEA} 25 | 26 | cv.setWindowTitle{"Display", "Result"} 27 | cv.imshow{"Display", result} 28 | cv.waitKey{0} 29 | -------------------------------------------------------------------------------- /demo/cuda/min.lua: -------------------------------------------------------------------------------- 1 | -- Calculates an elementwise minimum of two random matrices on GPU 2 | local cv = require "cv" 3 | require "cutorch" 4 | require "cv.cudaarithm" 5 | 6 | local n = 20 7 | 8 | local a = (torch.rand(n, n) * 10):int():float():cuda() 9 | local b = (torch.rand(n, n) * 10):int():float():cuda() 10 | local min_torch = torch.FloatTensor(n, n) 11 | 12 | for i = 1, n do 13 | for j = 1, n do 14 | min_torch[i][j] = math.min(a[i][j], b[i][j]) 15 | end 16 | end 17 | 18 | print("CUDA context initialization in OpenCV may take up to a minute. Hang on...") 19 | 20 | local min_cv = cv.cuda.min{a, b} 21 | print(min_cv:type()) 22 | 23 | if n <= 20 then 24 | print("Matrix of minimums by Torch:") 25 | print(min_torch) 26 | 27 | print("Matrix of minimums by CUDA-OpenCV:") 28 | print(min_cv) 29 | end 30 | 31 | if (min_torch:eq(min_cv:float()) - 1):sum() == 0 then 32 | print("OpenCV-CUDA's min() function works fine!") 33 | else 34 | print("You shouldn't see this message -- something went wrong! Please contact developers.") 35 | end -------------------------------------------------------------------------------- /demo/findContours.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv' 2 | require 'cv.imgproc' 3 | require 'cv.imgcodecs' 4 | require 'cv.highgui' 5 | 6 | if not arg[1] then 7 | print('`Usage: `th demo/descriptors.lua path-to-image`') 8 | print('Now using demo/data/lena.jpg') 9 | end 10 | 11 | local path = arg[1] or 'demo/data/lena.jpg' 12 | local image = cv.imread{path} 13 | 14 | if image:nDimension() == 0 then 15 | error('Couldn\'t load ' .. path) 16 | end 17 | 18 | cv.namedWindow{'win1'} 19 | cv.setWindowTitle{'win1', 'Original image'} 20 | cv.imshow{'win1', image} 21 | cv.waitKey{0} 22 | 23 | local imGray = cv.cvtColor{image, nil, cv.COLOR_BGR2GRAY} 24 | local _, thresh = cv.threshold{imGray, nil, 170, 255, 0} 25 | 26 | cv.setWindowTitle{'win1', 'Thresholded image'} 27 | cv.imshow{'win1', thresh} 28 | cv.waitKey{0} 29 | 30 | local contours, hierarchy = cv.findContours{thresh, true, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE} 31 | cv.drawContours{image, contours, -1, {0,255,0}, 3} 32 | 33 | cv.setWindowTitle{'win1', 'Contours'} 34 | cv.imshow{'win1', image} 35 | cv.waitKey{0} -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Egor Burkov and other contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /demo/cuda/convolution.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv' 2 | require 'cutorch' 3 | require 'cv.cudaarithm' 4 | require 'cv.highgui' 5 | require 'cv.imgcodecs' 6 | 7 | if not arg[1] then 8 | print('Usage: `th demo/cuda/convolution.lua path-to-image`') 9 | print('Now using demo/data/lena.jpg') 10 | end 11 | 12 | local image = cv.imread{arg[1] or 'demo/data/lena.jpg', cv.IMREAD_GRAYSCALE} 13 | 14 | if not image then 15 | print("Problem loading image\n") 16 | os.exit(0) 17 | end 18 | 19 | image = image:float():cuda() / 255 20 | 21 | local filter = torch.CudaTensor 22 | { 23 | {-0.3, -1.0, -0.3}, 24 | {-1.0, 5.2, -1.0}, 25 | {-0.3, -1.0, -0.3} 26 | } 27 | 28 | local conv = cv.cuda.Convolution{} 29 | local edges = conv:convolve{image, filter} 30 | 31 | cv.imshow{"Edges", edges:float()} 32 | cv.waitKey{0} 33 | 34 | require 'cv.cudafilters' 35 | 36 | -- You can also get `cv.CV_32F` value by calling 37 | -- `cv.tensorType(x)`, where x is a FloatTensor 38 | local Sobel = cv.cuda.createSobelFilter{cv.CV_32F, cv.CV_32F, 1, 1} 39 | edges = Sobel:apply{image} 40 | 41 | cv.imshow{"Edges", edges:float()} 42 | cv.waitKey{0} 43 | -------------------------------------------------------------------------------- /demo/videocap.lua: -------------------------------------------------------------------------------- 1 | -- a translated demo from here: 2 | -- http://docs.opencv.org/3.0-beta/modules/videoio/doc/reading_and_writing_video.html 3 | 4 | local cv = require 'cv' 5 | require 'cv.highgui' 6 | require 'cv.videoio' 7 | require 'cv.imgproc' 8 | 9 | local cap = cv.VideoCapture{device=0} 10 | if not cap:isOpened() then 11 | print("Failed to open the default camera") 12 | os.exit(-1) 13 | end 14 | 15 | cv.namedWindow{"edges", cv.WINDOW_AUTOSIZE} 16 | local _, frame = cap:read{} 17 | -- make a tensor of same type, but a 2-dimensional one 18 | local edges = frame.new(frame:size()[1], frame:size()[2]) 19 | 20 | while true do 21 | 22 | cv.cvtColor{frame, edges, cv.COLOR_BGR2GRAY} 23 | 24 | cv.GaussianBlur{ 25 | edges, 26 | ksize = {7,7}, 27 | sigmaX = 1.5, 28 | sigmaY = 1.5, 29 | dst = edges 30 | } 31 | 32 | cv.Canny{ 33 | image = edges, 34 | threshold1 = 0, 35 | threshold2 = 30, 36 | apertureSize = 3, 37 | edges = edges 38 | } 39 | 40 | cv.imshow{"edges", edges} 41 | if cv.waitKey{30} >= 0 then break end 42 | 43 | cap:read{frame} 44 | end 45 | -------------------------------------------------------------------------------- /demo/trackbar.lua: -------------------------------------------------------------------------------- 1 | -- A translated demo from here: 2 | -- http://docs.opencv.org/2.4/doc/tutorials/highgui/trackbar/trackbar.htm 3 | local cv = require 'cv' 4 | require 'cv.highgui' 5 | require 'cv.imgcodecs' -- for imread 6 | require 'cv.imgproc' -- for addWeighted 7 | 8 | local ffi = require 'ffi' 9 | local alphaSlider = ffi.new('int[1]', 40) 10 | local alphaSliderMax = 100 11 | 12 | local imgPrefixPath = 'demo/data/trackbar/' 13 | 14 | local src1 = cv.imread{imgPrefixPath.. 'LinuxLogo.png'} 15 | local src2 = cv.imread{imgPrefixPath..'WindowsLogo.png'} 16 | 17 | if src1:nElement() == 0 or src2:nElement() == 0 then 18 | error('Couldn\'t load images') 19 | end 20 | 21 | assert(src1:isSameSizeAs(src2)) 22 | local dst = src1.new(src1:size()) 23 | 24 | local function onTrackbar() 25 | local alpha = alphaSlider[0] / alphaSliderMax 26 | local beta = 1 - alpha 27 | -- can also be done in 2 lines with `torch.add()` 28 | cv.addWeighted {src1, alpha, src2, beta, 0.0, dst} 29 | cv.imshow {"Linear Blend", dst} 30 | end 31 | 32 | cv.namedWindow{'Linear Blend', cv.WINDOW_AUTOSIZE} 33 | 34 | local trackbarName = 'Alpha x '..alphaSliderMax 35 | cv.createTrackbar{trackbarName, 'Linear Blend', alphaSlider, alphaSliderMax, onTrackbar} 36 | 37 | onTrackbar() 38 | cv.waitKey{0} 39 | -------------------------------------------------------------------------------- /src/imgcodecs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | extern "C" 4 | struct TensorWrapper imread(const char *filename, int flags) 5 | { 6 | return TensorWrapper(cv::imread(filename, flags)); 7 | } 8 | 9 | extern "C" 10 | struct TensorArrayPlusBool imreadmulti(const char *filename, int flags) 11 | { 12 | TensorArrayPlusBool retval; 13 | std::vector mats; 14 | retval.val = cv::imreadmulti(filename, mats, flags); 15 | new (&retval.tensors) TensorArray(mats); 16 | return retval; 17 | } 18 | 19 | extern "C" 20 | bool imwrite(const char *filename, struct TensorWrapper img, struct TensorWrapper params) 21 | { 22 | if (params.isNull()) 23 | return cv::imwrite(filename, img.toMat()); 24 | else 25 | return cv::imwrite(filename, img.toMat(), params.toMat()); 26 | } 27 | 28 | extern "C" 29 | struct TensorWrapper imdecode(struct TensorWrapper buf, int flags) 30 | { 31 | return TensorWrapper(cv::imdecode(buf.toMat(), flags)); 32 | } 33 | 34 | extern "C" 35 | struct TensorWrapper imencode( 36 | const char *ext, struct TensorWrapper img, struct TensorWrapper params) 37 | { 38 | std::vector retval; 39 | cv::imencode(ext, img.toMat(), retval, params.toMat()); 40 | return TensorWrapper(cv::Mat(retval, true)); 41 | } 42 | -------------------------------------------------------------------------------- /demo/flann.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv' 2 | cv.flann = require 'cv.flann' 3 | require 'cv.imgproc' 4 | require 'cv.highgui' 5 | 6 | -- generate data 7 | local N_samples, N_features, fieldSize, N_query = 300, 2, 600, 20 8 | local samples = torch.rand(N_samples, N_features):float() * fieldSize 9 | 10 | -- create the index 11 | local params = cv.flann.KDTreeIndexParams{trees=10} 12 | local index = cv.flann.Index{samples, params, cv.FLANN_DIST_EUCLIDEAN} 13 | 14 | -- generate query point 15 | local query = torch.rand(1, N_features):float() * fieldSize 16 | local indices, dists = index:knnSearch{query, N_query} 17 | 18 | -- visualize data 19 | local img = torch.ByteTensor(fieldSize, fieldSize, 3) * 0 + 180 20 | 21 | -- draw query point 22 | cv.circle{img, {query[1][1], query[1][2]}, 4, {0, 150, 0}, 7} 23 | cv.circle{img, {query[1][1], query[1][2]}, 2, {0, 0 , 0}, 2} 24 | 25 | -- draw data points 26 | for i = 1,N_samples do 27 | cv.circle{img, {samples[i][1], samples[i][2]}, 2, {0, 0, 255}, 2} 28 | end 29 | 30 | -- draw search result 31 | for i = 1, N_query do 32 | local datum = {samples[indices[1][i]][1], samples[indices[1][i]][2]} 33 | cv.circle{img, datum, 5, {200, 0, 10}, 2} 34 | end 35 | 36 | cv.imshow{"Red: data, green: query, blue: "..N_query.." approximate NNs", img} 37 | cv.waitKey{0} -------------------------------------------------------------------------------- /demo/keypoints.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv' 2 | require 'cv.features2d' 3 | require 'cv.imgcodecs' 4 | require 'cv.highgui' 5 | 6 | if not arg[1] then 7 | print('`Usage: `th demo/descriptors.lua path-to-image`') 8 | print('Now using demo/data/lena.jpg') 9 | end 10 | 11 | local path = arg[1] or 'demo/data/lena.jpg' 12 | local image = cv.imread{path} 13 | 14 | if image:nDimension() == 0 then 15 | error('Couldn\'t load ' .. path) 16 | end 17 | 18 | cv.namedWindow{'win1'} 19 | cv.setWindowTitle{'win1', 'Original image'} 20 | cv.imshow{'win1', image} 21 | cv.waitKey{0} 22 | 23 | local AGAST = cv.AgastFeatureDetector{threshold=34} 24 | local keyPts = AGAST:detect{image} 25 | 26 | -- show keypoints to the user 27 | local imgWithAllKeypoints = cv.drawKeypoints{image, keyPts} 28 | cv.setWindowTitle{'win1', keyPts.size .. ' keypoints by AGAST'} 29 | cv.imshow{'win1', imgWithAllKeypoints} 30 | cv.waitKey{0} 31 | 32 | -- remove keypoints within 60 pixels from image border 33 | local imageSize = {image:size()[2], image:size()[1]} 34 | keyPts = cv.KeyPointsFilter.runByImageBorder{keyPts, imageSize, 60} 35 | 36 | -- show again, with reduced number of keypoints 37 | local imgWithSomeKeypoints = cv.drawKeypoints{image, keyPts} 38 | cv.setWindowTitle{'win1', keyPts.size .. ' remaining keypoints'} 39 | cv.imshow{'win1', imgWithSomeKeypoints} 40 | cv.waitKey{0} 41 | -------------------------------------------------------------------------------- /cv/core/init.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv._env' 2 | require 'cv.Classes' 3 | 4 | local ffi = require 'ffi' 5 | 6 | ffi.cdef[[ 7 | 8 | int getNumThreads(); 9 | 10 | void setNumThreads(int nthreads); 11 | 12 | struct TensorWrapper copyMakeBorder(struct TensorWrapper src, struct TensorWrapper dst, int top, 13 | int bottom, int left, int right, int borderType, 14 | struct ScalarWrapper value); 15 | ]] 16 | 17 | local C = ffi.load(cv.libPath('core')) 18 | 19 | function cv.getNumThreads(t) 20 | local argRules = { 21 | } 22 | return C.getNumThreads(cv.argcheck(t, argRules)) 23 | end 24 | 25 | function cv.setNumThreads(t) 26 | local argRules = { 27 | {"nthreads", required = true} 28 | } 29 | return C.setNumThreads(cv.argcheck(t, argRules)) 30 | end 31 | 32 | function cv.copyMakeBorder(t) 33 | local argRules = { 34 | {"src", required = true, operator = cv.wrap_tensor}, 35 | {"dst", default = nil, operator = cv.wrap_tensor}, 36 | {"top", required = true}, 37 | {"bottom", required = true}, 38 | {"left", required = true}, 39 | {"right", required = true}, 40 | {"borderType", required = true}, 41 | {"value", default = {0,0,0,0} , operator = cv.Scalar} 42 | } 43 | return cv.unwrap_tensors(C.copyMakeBorder(cv.argcheck(t, argRules))) 44 | end 45 | 46 | return cv -------------------------------------------------------------------------------- /src/xphoto.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | extern "C" 4 | struct TensorWrapper xphoto_autowbGrayworld( 5 | struct TensorWrapper src, struct TensorWrapper dst, float thresh) 6 | { 7 | MatT dst_mat = dst.toMatT(); 8 | cv::xphoto::autowbGrayworld(src.toMat(), dst_mat, thresh); 9 | return TensorWrapper(dst_mat); 10 | } 11 | 12 | extern "C" 13 | struct TensorWrapper xphoto_balanceWhite( 14 | struct TensorWrapper src, struct TensorWrapper dst, int algorithmType, 15 | float inputMin, float inputMax, float outputMin, float outputMax) 16 | { 17 | MatT dst_mat = dst.toMatT(); 18 | cv::xphoto::balanceWhite(src.toMat(), dst_mat.mat, algorithmType, inputMin, inputMax, outputMin, outputMax); 19 | return TensorWrapper(dst_mat); 20 | } 21 | 22 | extern "C" 23 | struct TensorWrapper xphoto_dctDenoising( 24 | struct TensorWrapper src, struct TensorWrapper dst, double sigma, int psize) 25 | { 26 | MatT dst_mat = dst.toMatT(); 27 | cv::xphoto::balanceWhite(src.toMat(), dst_mat.mat, sigma, psize); 28 | return TensorWrapper(dst_mat); 29 | } 30 | 31 | extern "C" 32 | struct TensorWrapper xphoto_inpaint( 33 | struct TensorWrapper src, struct TensorWrapper mask, 34 | struct TensorWrapper dst, int algorithmType) 35 | { 36 | MatT dst_mat = dst.toMatT(); 37 | cv::xphoto::inpaint(src.toMat(), mask.toMat(), dst_mat.mat, algorithmType); 38 | return TensorWrapper(dst_mat); 39 | } 40 | -------------------------------------------------------------------------------- /tests/conversion.lua: -------------------------------------------------------------------------------- 1 | -- Currently no unit tests are present here. 2 | -- Let this be the future site for them 3 | 4 | local cv = require 'cv' 5 | 6 | local ffi = require 'ffi' 7 | 8 | ffi.cdef[[ 9 | void test_tensor_to_mat(struct TensorWrapper tensor); 10 | struct TensorWrapper test_mat_to_tensor(); 11 | ]] 12 | 13 | local ok, C = pcall(ffi.load, cv.libPath('Tests')) 14 | if not ok then 15 | print('torch-opencv is built with BUILD_TESTS = OFF. Aborting.') 16 | os.exit(-1) 17 | end 18 | 19 | -- prints Tensor from OpenCV 20 | function test_tensor_to_mat(tensor) 21 | assert(tensor:dim() <= 2 or tensor:dim() == 3 and tensor:size(3) <= 4) 22 | C.test_tensor_to_mat(cv.wrap_tensor(tensor)) 23 | end 24 | 25 | -- creates a Mat and returns it as a Tensor 26 | function test_mat_to_tensor() 27 | return cv.unwrap_tensors(C.test_mat_to_tensor()) 28 | end 29 | 30 | -- *************** testing *************** 31 | 32 | local tensor_a = torch.IntTensor(2, 2, 2) 33 | tensor_a[1][1][1] = 1 34 | tensor_a[1][2][1] = 2 35 | tensor_a[2][1][1] = 3 36 | tensor_a[2][2][1] = 4 37 | tensor_a[1][1][2] = 5 38 | tensor_a[1][2][2] = 6 39 | tensor_a[2][1][2] = 7 40 | tensor_a[2][2][2] = 8 41 | 42 | test_tensor_to_mat(tensor_a) 43 | 44 | local tensor_b = torch.DoubleTensor(3, 3) 45 | for i=1,3 do 46 | for j=1,3 do 47 | tensor_b[i][j] = j^i 48 | end 49 | end 50 | 51 | test_tensor_to_mat(tensor_b) 52 | 53 | local another_tensor = test_mat_to_tensor() 54 | print(another_tensor) 55 | -------------------------------------------------------------------------------- /demo/cuda/resize.lua: -------------------------------------------------------------------------------- 1 | require 'cutorch' 2 | 3 | local cv = require 'cv' 4 | require 'cv.cudawarping' -- cv.cuda.resize 5 | require 'cv.imgproc' -- cv.resize 6 | require 'cv.highgui' -- cv.imshow 7 | require 'cv.imgcodecs' -- cv.imread 8 | 9 | if not arg[1] then 10 | print('Usage: `th demo/cuda/resize.lua path-to-image`') 11 | print('Now using demo/data/lena.jpg') 12 | print('') 13 | end 14 | 15 | local img = cv.imread {arg[1] or 'demo/data/lena.jpg', cv.IMREAD_COLOR}:float() / 255 16 | local imgCUDA = img:cuda() 17 | 18 | require 'xlua' 19 | local numIterations, dsize = 2000, {1024, 768} 20 | 21 | local resized = cv.resize{img, dsize} 22 | local resizedCUDA = torch.CudaTensor(resized:size()) 23 | 24 | print(('Doing `cv.resize{}` (CPU) %d times (OpenCV\'s number of threads is %d):') 25 | :format(numIterations, cv.getNumThreads{})) 26 | local timer = torch.Timer() 27 | 28 | for iter = 1,numIterations do 29 | cv.resize{img, dsize, dst=resized} 30 | if iter % 100 == 0 then xlua.progress(iter, numIterations) end 31 | end 32 | local timeCPU = timer:time().real 33 | 34 | print(('Doing `cv.cuda.resize{}` (GPU) %d times:'):format(numIterations)) 35 | timer:reset() 36 | 37 | for iter = 1,numIterations do 38 | cv.cuda.resize{imgCUDA, dsize, dst=resizedCUDA} 39 | if iter % 100 == 0 then xlua.progress(iter, numIterations) end 40 | end 41 | cutorch.synchronize() 42 | local timeGPU = timer:time().real 43 | 44 | -- a technical test to check if Tensor freeing works without errors 45 | for iter = 1,40 do 46 | local _ = cv.cuda.resize{imgCUDA, dsize} 47 | end 48 | collectgarbage() 49 | 50 | local title = 51 | ("Lena resized to 1024x768 by your GPU (%.3f times faster than CPU)"):format(timeCPU / timeGPU) 52 | cv.imshow{title, resizedCUDA:float()} 53 | cv.waitKey{0} 54 | -------------------------------------------------------------------------------- /demo/filtering.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv' 2 | require 'cv.imgproc' 3 | require 'cv.imgcodecs' 4 | require 'cv.highgui' 5 | 6 | if not arg[1] then 7 | print('Usage: `th demo/filtering.lua path-to-image`') 8 | print('Now using demo/data/lena.jpg') 9 | end 10 | 11 | local path = arg[1] or 'demo/data/lena.jpg' 12 | local image = cv.imread{path} 13 | 14 | if image:nDimension() == 0 then 15 | error('Couldn\'t load ' .. path) 16 | end 17 | 18 | cv.putText{ 19 | img=image, 20 | text="Some text on top of the image", 21 | org={x=15, y=50}, 22 | fontFace=cv.FONT_HERSHEY_DUPLEX, 23 | fontScale=0.95, 24 | color={50, 200, 200}, 25 | thickness=2, 26 | } 27 | 28 | cv.imshow{winname="Original image with text", image=image} 29 | cv.waitKey{0} 30 | 31 | -- output to another Tensor of same size & type... 32 | local image_A = image:clone() 33 | local w = cv.GaussianBlur{src=image, ksize={7, 7}, sigmaX=3.5, dst=image_A, sigmaY=3.5} 34 | 35 | -- or to a return value... 36 | local image_B = cv.GaussianBlur{src=image, ksize={7, 7}, sigmaX=3.5, sigmaY=3.5} 37 | 38 | -- or filter in-place. 39 | -- we can also specify ksize as a string-number table, 40 | -- and it's not necessary to use named agruments: 41 | cv.GaussianBlur{image, {width=7, height=7}, 3.5, image, 3.5} 42 | 43 | -- results are equal 44 | assert((image:eq(image_B) - 1):sum() == 0) 45 | assert((image:eq(image_A) - 1):sum() == 0) 46 | 47 | cv.imshow{"Blurred", image_B} 48 | cv.waitKey{0} 49 | 50 | -- output to a single-channel ByteTensor of same size 51 | local edges = torch.ByteTensor(image:size()[1], image:size()[2]) 52 | cv.Canny{image=image, edges=edges, threshold1=0, threshold2=30} 53 | 54 | -- or to a return value 55 | local edges2 = cv.Canny{image=image, threshold1=0, threshold2=30} 56 | 57 | -- results are equal 58 | assert((edges:eq(edges2) - 1):sum() == 0) 59 | 60 | cv.imshow{"Edges by Canny", edges2} 61 | cv.waitKey{0} 62 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | compiler: 3 | - gcc 4 | os: 5 | - linux 6 | - osx 7 | cache: 8 | directories: 9 | - $HOME/OpenBlasInstall 10 | env: 11 | - TORCH_LUA_VERSION=LUAJIT21 12 | - TORCH_LUA_VERSION=LUA51 13 | - TORCH_LUA_VERSION=LUA52 14 | addons: 15 | apt: 16 | packages: 17 | - cmake 18 | - gfortran 19 | - gcc-multilib 20 | - gfortran-multilib 21 | - liblapack-dev 22 | - build-essential 23 | - gcc 24 | - g++ 25 | - curl 26 | - cmake 27 | - libreadline-dev 28 | - git-core 29 | - libqt4-core 30 | - libqt4-gui 31 | - libqt4-dev 32 | - libjpeg-dev 33 | - libpng-dev 34 | - ncurses-dev 35 | - imagemagick 36 | - libzmq3-dev 37 | - gfortran 38 | - unzip 39 | - gnuplot 40 | - gnuplot-x11 41 | - libfftw3-dev 42 | - sox 43 | - libsox-dev 44 | - libsox-fmt-all 45 | - libgraphicsmagick1-dev 46 | - graphicsmagick 47 | before_script: 48 | - export ROOT_TRAVIS_DIR=$(pwd) 49 | - export INSTALL_PREFIX=~/torch/install 50 | - ls $HOME/OpenBlasInstall/lib || (cd /tmp/ && git clone https://github.com/xianyi/OpenBLAS.git -b master && cd OpenBLAS && (make NO_AFFINITY=1 -j$(getconf _NPROCESSORS_ONLN) 2>/dev/null >/dev/null) && make PREFIX=$HOME/OpenBlasInstall install) 51 | - git clone https://github.com/torch/distro.git ~/torch --recursive 52 | - cd ~/torch && ./install.sh -b 53 | - source ~/torch/install/bin/torch-activate 54 | - cd $ROOT_TRAVIS_DIR 55 | - git clone https://github.com/Itseez/opencv 56 | - cd opencv 57 | - git checkout tags/3.1.0 58 | - mkdir -p build && cd build 59 | - cmake -DWITH_PYTHON=OFF -DWITH_OPENCL=OFF -DWITH_QUICKTIME=OFF -DWITH_GSTREAMER=OFF -DWITH_FFMPEG=OFF -DCMAKE_BUILD_TYPE=Release .. && make 60 | - cd $ROOT_TRAVIS_DIR 61 | - git clone https://github.com/VisionLabs/torch-opencv 62 | script: 63 | - cd torch-opencv 64 | OpenCV_DIR=${ROOT_DIR}/opencv/build luarocks make 65 | -------------------------------------------------------------------------------- /include/highgui.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | extern "C" 5 | void imshow(const char *winname, struct TensorWrapper mat); 6 | 7 | extern "C" 8 | int waitKey(int delay); 9 | 10 | extern "C" 11 | void namedWindow(const char *winname, int flags); 12 | 13 | extern "C" 14 | void destroyWindow(const char *winname); 15 | 16 | extern "C" 17 | void destroyAllWindows(); 18 | 19 | extern "C" 20 | int startWindowThread(); 21 | 22 | extern "C" 23 | void resizeWindow(const char *winname, int width, int height); 24 | 25 | extern "C" 26 | void moveWindow(const char *winname, int x, int y); 27 | 28 | extern "C" 29 | void setWindowProperty(const char *winname, int prop_id, double prop_value); 30 | 31 | extern "C" 32 | void setWindowTitle(const char *winname, const char *title); 33 | 34 | extern "C" 35 | double getWindowProperty(const char *winname, int prop_id); 36 | 37 | extern "C" 38 | void setMouseCallback(const char *winname, cv::MouseCallback onMouse, void *userdata); 39 | 40 | extern "C" 41 | int getMouseWheelData(int flags); 42 | 43 | extern "C" 44 | int createTrackbar( 45 | const char *trackbarname, const char *winname, int *value, 46 | int count, cv::TrackbarCallback onChange, void *userdata); 47 | 48 | extern "C" 49 | int getTrackbarPos(const char *trackbarname, const char *winname); 50 | 51 | extern "C" 52 | void setTrackbarPos(const char *trackbarname, const char *winname, int pos); 53 | 54 | extern "C" 55 | void setTrackbarMax(const char *trackbarname, const char *winname, int maxval); 56 | 57 | extern "C" 58 | void updateWindow(const char *winname); 59 | 60 | extern "C" 61 | void displayOverlay(const char *winname, const char *text, int delayms); 62 | 63 | extern "C" 64 | void displayStatusBar(const char *winname, const char *text, int delayms); 65 | 66 | extern "C" 67 | void saveWindowParameters(const char *windowName); 68 | 69 | extern "C" 70 | void loadWindowParameters(const char *windowName); -------------------------------------------------------------------------------- /cv/_env_cuda.lua: -------------------------------------------------------------------------------- 1 | require 'cutorch' 2 | local cuda = {} 3 | 4 | cuda.SF_UYVY = 0 5 | cuda.SF_YUY2 = 1 6 | cuda.SF_YV12 = 2 7 | cuda.SF_NV12 = 3 8 | cuda.SF_IYUV = 4 9 | cuda.SF_BGR = 5 10 | cuda.SF_GRAY = 5 11 | 12 | cuda.CODEC_MPEG1 = 0 13 | cuda.CODEC_MPEG2 = 1 14 | cuda.CODEC_MPEG4 = 2 15 | cuda.CODEC_VC1 = 3 16 | cuda.CODEC_H264 = 4 17 | cuda.CODEC_JPEG = 5 18 | cuda.CODEC_H264_SVC = 6 19 | cuda.CODEC_H264_MVC = 7 20 | cuda.CODEC_Uncompressed_YUV420 = 1230591318 21 | cuda.CODEC_Uncompressed_YV12 = 1498820914 22 | cuda.CODEC_Uncompressed_NV12 = 1314271538 23 | cuda.CODEC_Uncompressed_YUYV = 1498765654 24 | cuda.CODEC_Uncompressed_UYVY = 1431918169 25 | 26 | cuda.CHROMA_FORMAT_Monochrome = 0 27 | cuda.CHROMA_FORMAT_YUV420 = 1 28 | cuda.CHROMA_FORMAT_YUV422 = 2 29 | cuda.CHROMA_FORMAT_YUV444 = 3 30 | 31 | cuda.COLOR_BayerBG2BGR_MHT = 256 32 | cuda.COLOR_BayerGB2BGR_MHT = 257 33 | cuda.COLOR_BayerRG2BGR_MHT = 258 34 | cuda.COLOR_BayerGR2BGR_MHT = 259 35 | 36 | cuda.COLOR_BayerBG2RGB_MHT = COLOR_BayerRG2BGR_MHT 37 | cuda.COLOR_BayerGB2RGB_MHT = COLOR_BayerGR2BGR_MHT 38 | cuda.COLOR_BayerRG2RGB_MHT = COLOR_BayerBG2BGR_MHT 39 | cuda.COLOR_BayerGR2RGB_MHT = COLOR_BayerGB2BGR_MHT 40 | 41 | cuda.COLOR_BayerBG2GRAY_MHT = 260 42 | cuda.COLOR_BayerGB2GRAY_MHT = 261 43 | cuda.COLOR_BayerRG2GRAY_MHT = 262 44 | cuda.COLOR_BayerGR2GRAY_MHT = 263 45 | 46 | cuda.ALPHA_OVER = 0 47 | cuda.ALPHA_IN = 1 48 | cuda.ALPHA_OUT = 2 49 | cuda.ALPHA_ATOP = 3 50 | cuda.ALPHA_XOR = 4 51 | cuda.ALPHA_PLUS = 5 52 | cuda.ALPHA_OVER_PREMUL = 6 53 | cuda.ALPHA_IN_PREMUL = 7 54 | cuda.ALPHA_OUT_PREMUL = 8 55 | cuda.ALPHA_ATOP_PREMUL = 9 56 | cuda.ALPHA_XOR_PREMUL = 10 57 | cuda.ALPHA_PLUS_PREMUL = 11 58 | cuda.ALPHA_PREMUL = 12 59 | 60 | cuda.DESCR_FORMAT_ROW_BY_ROW = 0 61 | cuda.DESCR_FORMAT_COL_BY_COL = 1 62 | 63 | local ffi = require 'ffi' 64 | 65 | ffi.cdef[[ 66 | struct cutorchInfo { 67 | int deviceID; 68 | struct THCState *state; 69 | }; 70 | ]] 71 | 72 | function cuda._info() 73 | return ffi.new('struct cutorchInfo', cutorch.getDevice(), cutorch.getState()) 74 | end 75 | 76 | return cuda 77 | -------------------------------------------------------------------------------- /include/cudacodec.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | namespace cudacodec = cv::cudacodec; 6 | 7 | extern "C" 8 | struct cudacodec::EncoderParams EncoderParams_ctor_default(); 9 | 10 | extern "C" 11 | struct cudacodec::EncoderParams EncoderParams_ctor(const char *configFile); 12 | 13 | extern "C" 14 | void EncoderParams_saveCuda(struct cudacodec::EncoderParams params, const char *configFile); 15 | 16 | struct VideoWriterPtr { 17 | void *ptr; 18 | 19 | inline cudacodec::VideoWriter * operator->() { return static_cast(ptr); } 20 | inline VideoWriterPtr(cudacodec::VideoWriter *ptr) { this->ptr = ptr; } 21 | inline cudacodec::VideoWriter & operator*() { return *static_cast(this->ptr); } 22 | }; 23 | 24 | struct VideoReaderPtr { 25 | void *ptr; 26 | 27 | inline cudacodec::VideoReader * operator->() { return static_cast(ptr); } 28 | inline VideoReaderPtr(cudacodec::VideoReader *ptr) { this->ptr = ptr; } 29 | inline cudacodec::VideoReader & operator*() { return *static_cast(this->ptr); } 30 | }; 31 | 32 | extern "C" 33 | struct VideoWriterPtr VideoWriter_ctorCuda( 34 | const char *filename, struct SizeWrapper frameSize, 35 | double fps, struct cudacodec::EncoderParams params, int format); 36 | 37 | extern "C" 38 | void VideoWriter_dtorCuda(struct VideoWriterPtr ptr); 39 | 40 | extern "C" 41 | void VideoWriter_writeCuda(struct VideoWriterPtr ptr, struct TensorWrapper frame, bool lastFrame); 42 | 43 | extern "C" 44 | struct cudacodec::EncoderParams VideoWriter_getEncoderParams(struct VideoWriterPtr ptr); 45 | 46 | extern "C" 47 | struct VideoReaderPtr VideoReader_ctorCuda(const char *filename); 48 | 49 | extern "C" 50 | void VideoReader_dtorCuda(struct VideoReaderPtr ptr); 51 | 52 | extern "C" 53 | struct TensorWrapper VideoReader_nextFrameCuda( 54 | struct cutorchInfo info, struct VideoReaderPtr ptr, struct TensorWrapper frame); 55 | 56 | extern "C" 57 | struct cudacodec::FormatInfo VideoReader_format(struct VideoReaderPtr ptr); -------------------------------------------------------------------------------- /tests/test.lua: -------------------------------------------------------------------------------- 1 | require 'image' 2 | local cv = require 'cv' 3 | require 'cv.imgcodecs' 4 | require 'cv.imgproc' 5 | 6 | local mytester = torch.Tester() 7 | local cvtest = torch.TestSuite() 8 | 9 | local lena_path = 'demo/data/lena.jpg' 10 | 11 | local function HWCBGR_2_CHWRGB(im) 12 | return im:permute(3,1,2):index(1,torch.LongTensor{3,2,1}) 13 | end 14 | 15 | -- test against torch/image 16 | -- assuming that test is called from root path 17 | function cvtest.imread() 18 | local ref_image = image.load(lena_path, 3, 'byte') 19 | local cv_image = HWCBGR_2_CHWRGB(cv.imread{lena_path}) 20 | mytester:asserteq((ref_image - cv_image):float():abs():max(), 0, 'imread byte difference') 21 | end 22 | 23 | function cvtest.resize() 24 | local torch_image = image.load(lena_path, 3, 'byte') 25 | local cv_image = cv.imread{lena_path} 26 | 27 | local M = 256 28 | 29 | local interp_methods = { 30 | {torch='simple', cv=cv.INTER_NEAREST, error = 0}, 31 | {torch='bilinear', cv=cv.INTER_LINEAR, error = 0.5}, -- implementations are different 32 | } 33 | 34 | for i,method in ipairs(interp_methods) do 35 | local torch_resized = image.scale(torch_image, M, M, method.torch) 36 | local cv_resized = cv.resize{src = cv_image, dsize = {M,M}, interpolation = method.cv} 37 | local diff = torch_resized - HWCBGR_2_CHWRGB(cv_resized) 38 | mytester:assertle(diff:float():abs():mean(), method.error, 'imread byte difference') 39 | end 40 | end 41 | 42 | function cvtest.flip() 43 | local torch_image = image.load(lena_path, 3, 'byte') 44 | local cv_image = cv.imread{lena_path} 45 | 46 | function image.hvflip(src) 47 | return image.vflip(image.hflip(src)) 48 | end 49 | 50 | for i,v in ipairs{ 51 | {f='hflip', code=1}, 52 | {f='vflip', code=0}, 53 | {f='hvflip', code=-1}, 54 | } do 55 | local torch_hflipped = image[v.f](torch_image) 56 | local cv_hflipped = cv.flip{src = cv_image, flipCode = v.code} 57 | local diff = torch_hflipped - HWCBGR_2_CHWRGB(cv_hflipped) 58 | mytester:asserteq(diff:float():abs():max(), 0, 'imread byte difference') 59 | end 60 | end 61 | 62 | mytester:add(cvtest) 63 | mytester:run() 64 | -------------------------------------------------------------------------------- /src/Classes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // FileNode 4 | 5 | extern "C" 6 | struct FileNodePtr FileNode_ctor() { 7 | return new cv::FileNode(); 8 | } 9 | 10 | extern "C" 11 | void FileNode_dtor(FileNodePtr ptr) { 12 | delete static_cast(ptr.ptr); 13 | } 14 | 15 | // FileStorage 16 | 17 | extern "C" 18 | struct FileStoragePtr FileStorage_ctor_default() { 19 | return new cv::FileStorage(); 20 | } 21 | 22 | extern "C" 23 | struct FileStoragePtr FileStorage_ctor(const char *source, int flags, const char *encoding) { 24 | return new cv::FileStorage(source, flags, encoding); 25 | } 26 | 27 | extern "C" 28 | void FileStorage_dtor(FileStoragePtr ptr) { 29 | delete static_cast(ptr.ptr); 30 | } 31 | 32 | extern "C" 33 | bool FileStorage_open(FileStoragePtr ptr, const char *filename, int flags, const char *encoding) { 34 | return ptr->open(filename, flags, encoding); 35 | } 36 | 37 | extern "C" 38 | bool FileStorage_isOpened(FileStoragePtr ptr) { 39 | return ptr->isOpened(); 40 | } 41 | 42 | extern "C" 43 | void FileStorage_release(FileStoragePtr ptr) { 44 | ptr->release(); 45 | } 46 | 47 | extern "C" 48 | const char *FileStorage_releaseAndGetString(FileStoragePtr ptr) { 49 | return ptr->releaseAndGetString().c_str(); 50 | } 51 | 52 | // Algorithm 53 | 54 | extern "C" 55 | struct AlgorithmPtr Algorithm_ctor() { 56 | return new cv::Algorithm(); 57 | } 58 | 59 | extern "C" 60 | void Algorithm_dtor(AlgorithmPtr ptr) { 61 | delete static_cast(ptr.ptr); 62 | } 63 | 64 | extern "C" 65 | void Algorithm_clear(AlgorithmPtr ptr) { 66 | ptr->clear(); 67 | } 68 | 69 | extern "C" 70 | void Algorithm_write(AlgorithmPtr ptr, FileStoragePtr fileStorage) { 71 | ptr->write(*fileStorage); 72 | } 73 | 74 | extern "C" 75 | void Algorithm_read(AlgorithmPtr ptr, FileNodePtr fileNode) { 76 | ptr->read(*fileNode); 77 | } 78 | 79 | extern "C" 80 | bool Algorithm_empty(AlgorithmPtr ptr) { 81 | return ptr->empty(); 82 | } 83 | 84 | extern "C" 85 | void Algorithm_save(AlgorithmPtr ptr, const char *filename) { 86 | ptr->save(filename); 87 | } 88 | 89 | extern "C" 90 | const char *Algorithm_getDefaultName(AlgorithmPtr ptr) { 91 | return ptr->getDefaultName().c_str(); 92 | } -------------------------------------------------------------------------------- /cv/imgcodecs/init.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv._env' 2 | 3 | local ffi = require 'ffi' 4 | 5 | ffi.cdef[[ 6 | struct TensorWrapper imread(const char *filename, int flags); 7 | 8 | struct TensorArrayPlusBool imreadmulti(const char *filename, int flags); 9 | 10 | bool imwrite(const char *filename, struct TensorWrapper img, struct TensorWrapper params); 11 | 12 | struct TensorWrapper imdecode(struct TensorWrapper buf, int flags); 13 | 14 | struct TensorWrapper imencode( 15 | const char *ext, struct TensorWrapper img, struct TensorWrapper params); 16 | ]] 17 | 18 | local C = ffi.load(cv.libPath('imgcodecs')) 19 | 20 | function cv.imread(t) 21 | local argRules = { 22 | {"filename", required = true}, 23 | {"flags", default = cv.IMREAD_COLOR} 24 | } 25 | local filename, flags = cv.argcheck(t, argRules) 26 | return cv.unwrap_tensors(C.imread(filename, flags)) 27 | end 28 | 29 | function cv.imreadmulti(t) 30 | local argRules = { 31 | {"filename", required = true}, 32 | {"flags", default = cv.IMREAD_ANYCOLOR} 33 | } 34 | local filename, flags = cv.argcheck(t, argRules) 35 | 36 | return cv.unwrap_tensors(C.imreadmulti(filename, flags), true) 37 | end 38 | 39 | function cv.imwrite(t) 40 | local argRules = { 41 | {"filename", required = true}, 42 | {"img", required = true}, 43 | {"params", default = nil, 44 | operator = function(...) if ... then return torch.IntTensor(...) end end} 45 | } 46 | local filename, img, params = cv.argcheck(t, argRules) 47 | 48 | return C.imwrite(filename, cv.wrap_tensor(img), cv.wrap_tensor(params)) 49 | end 50 | 51 | function cv.imdecode(t) 52 | local argRules = { 53 | {"buf", required = true}, 54 | {"flags", required = true} 55 | } 56 | local buf, flags = cv.argcheck(t, argRules) 57 | 58 | return cv.unwrap_tensors(C.imdecode(cv.wrap_tensor(buf), flags)) 59 | end 60 | 61 | function cv.imencode(t) 62 | local argRules = { 63 | {"ext", required = true}, 64 | {"img", required = true}, 65 | {"params", default = nil} 66 | } 67 | local ext, img, params = cv.argcheck(t, argRules) 68 | 69 | return cv.unwrap_tensors(C.imencode(ext, cv.wrap_tensor(img), cv.wrap_tensor(params))) 70 | end 71 | 72 | return cv 73 | -------------------------------------------------------------------------------- /src/cudacodec.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | extern "C" 4 | struct cudacodec::EncoderParams EncoderParams_ctor_default() 5 | { 6 | return cudacodec::EncoderParams(); 7 | } 8 | 9 | extern "C" 10 | struct cudacodec::EncoderParams EncoderParams_ctor(const char *configFile) 11 | { 12 | return cudacodec::EncoderParams(configFile); 13 | } 14 | 15 | extern "C" 16 | void EncoderParams_saveCuda(struct cudacodec::EncoderParams params, const char *configFile) 17 | { 18 | params.save(configFile); 19 | } 20 | 21 | extern "C" 22 | struct VideoWriterPtr VideoWriter_ctorCuda( 23 | const char *filename, struct SizeWrapper frameSize, 24 | double fps, struct cudacodec::EncoderParams params, int format) 25 | { 26 | return rescueObjectFromPtr(cudacodec::createVideoWriter( 27 | cv::String(filename), frameSize, fps, params, 28 | static_cast(format))); 29 | } 30 | 31 | extern "C" 32 | void VideoWriter_dtorCuda(struct VideoWriterPtr ptr) 33 | { 34 | delete static_cast(ptr.ptr); 35 | } 36 | 37 | extern "C" 38 | void VideoWriter_writeCuda(struct VideoWriterPtr ptr, struct TensorWrapper frame, bool lastFrame) 39 | { 40 | ptr->write(frame.toGpuMat(), lastFrame); 41 | } 42 | 43 | extern "C" 44 | struct cudacodec::EncoderParams VideoWriter_getEncoderParams(struct VideoWriterPtr ptr) 45 | { 46 | return ptr->getEncoderParams(); 47 | } 48 | 49 | extern "C" 50 | struct VideoReaderPtr VideoReader_ctorCuda(const char *filename) 51 | { 52 | return rescueObjectFromPtr(cudacodec::createVideoReader(cv::String(filename))); 53 | } 54 | 55 | extern "C" 56 | void VideoReader_dtorCuda(struct VideoReaderPtr ptr) 57 | { 58 | delete static_cast(ptr.ptr); 59 | } 60 | 61 | extern "C" 62 | struct TensorWrapper VideoReader_nextFrameCuda( 63 | struct cutorchInfo info, struct VideoReaderPtr ptr, struct TensorWrapper frame) 64 | { 65 | if (frame.isNull()) { 66 | cuda::GpuMat retval; 67 | ptr->nextFrame(retval); 68 | return TensorWrapper(retval, info.state); 69 | } else { 70 | ptr->nextFrame(frame.toGpuMat()); 71 | return frame; 72 | } 73 | } 74 | 75 | extern "C" 76 | struct cudacodec::FormatInfo VideoReader_format(struct VideoReaderPtr ptr) 77 | { 78 | return ptr->format(); 79 | } 80 | -------------------------------------------------------------------------------- /demo/SVM.lua: -------------------------------------------------------------------------------- 1 | --[[ 2 | A translated demo from here: 3 | http://docs.opencv.org/3.0.0/d1/d73/tutorial_introduction_to_svm.html 4 | 5 | When running the above example in C++ (OpenCV 3.0.0), for some reason .getSupportVectors() 6 | outputs [-0.008130081, 0.008163265]. That's why here I've set kernel type to quadratic. 7 | 8 | Original version by @szagoruyko 9 | --]] 10 | 11 | local cv = require 'cv' 12 | require 'cv.imgproc' 13 | require 'cv.imgcodecs' 14 | require 'cv.highgui' 15 | cv.ml = require 'cv.ml' 16 | 17 | -- Data for visual representation 18 | local width, height = 512, 512 19 | local im = torch.ByteTensor(height, width, 3):zero() 20 | 21 | -- Set up training data 22 | local labelsMat = torch.IntTensor{1, -1, -1, -1} 23 | local trainingDataMat = torch.FloatTensor{ {501, 10}, {255, 10}, {501, 255}, {10, 501} } 24 | 25 | -- Set up SVM's parameters 26 | local svm = cv.ml.SVM() 27 | svm:setType {cv.ml.SVM_C_SVC} 28 | svm:setKernel {cv.ml.SVM_POLY} 29 | svm:setDegree {2} 30 | svm:setTermCriteria {cv.TermCriteria{cv.TermCriteria_MAX_ITER, 100, 1e-6}} 31 | 32 | -- Train the SVM 33 | svm:train{trainingDataMat, cv.ml.ROW_SAMPLE, labelsMat} 34 | 35 | -- Show the decision regions given by the SVM 36 | local timer = torch.Timer() 37 | 38 | local green, blue = torch.ByteTensor{0,255,0}, torch.ByteTensor{255,0,0} 39 | 40 | for i=1,im:size(1) do 41 | for j=1,im:size(2) do 42 | local response = svm:predict{torch.FloatTensor{{j, i}}} 43 | 44 | im[{i,j,{}}]:copy(response == 1 and green or blue) 45 | end 46 | end 47 | 48 | print("SVM evaluation time: " .. timer:time().real .. " seconds") 49 | 50 | -- Show the training data 51 | local thickness = -1 52 | local lineType = 8 53 | cv.circle{ im, {501, 10}, 5, { 0, 0, 0}, thickness, lineType } 54 | cv.circle{ im, {255, 10}, 5, {255, 255, 255}, thickness, lineType } 55 | cv.circle{ im, {501, 255}, 5, {255, 255, 255}, thickness, lineType } 56 | cv.circle{ im, { 10, 501}, 5, {255, 255, 255}, thickness, lineType } 57 | 58 | -- Show support vectors 59 | thickness = 2 60 | lineType = 8 61 | local sv = svm:getSupportVectors() 62 | 63 | for i=1,sv:size(1) do 64 | cv.circle{im, {sv[i][1], sv[i][2]}, 6, {128,128,128}, thickness, lineType} 65 | end 66 | 67 | cv.imwrite{"result.png", im} -- save the image 68 | cv.imshow{"SVM Simple Example", im} -- show it to the user 69 | cv.waitKey{0} 70 | -------------------------------------------------------------------------------- /demo/calibrateCamera.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv' 2 | require 'cv.imgproc' 3 | require 'cv.imgcodecs' 4 | require 'cv.highgui' 5 | require 'cv.calib3d' 6 | 7 | local numImages = 7 8 | local patternSize = cv.Size(4, 3) 9 | local imageSize = cv.Size(640, 360) 10 | local imagesPathPrefix = 'demo/data/calibrateCamera/' 11 | 12 | local img = {} 13 | 14 | for i = 1, numImages do 15 | local path = imagesPathPrefix..'template'..i..'.jpg' 16 | img[i] = cv.imread{path} 17 | 18 | if img[i]:nElement() == 0 then 19 | error('Couldn\'t load ' .. imagesPathPrefix..'template'..i..'.jpg') 20 | end 21 | end 22 | 23 | local corners = {} 24 | local isFound = false 25 | 26 | for i = 1, numImages do 27 | isFound, corners[i] = cv.findChessboardCorners{image = img[i], patternSize = patternSize} 28 | if not isFound then 29 | print('Chessboard at image #'..i..' was NOT found!') 30 | end 31 | 32 | local img_gray = cv.cvtColor{img[i], code = cv.COLOR_BGR2GRAY} 33 | cv.cornerSubPix{ 34 | image = img_gray, 35 | corners = corners[i], 36 | winSize = cv.Size(11, 11), 37 | zeroZone = cv.Size(-1, -1), 38 | criteria = {cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.1} 39 | } 40 | cv.drawChessboardCorners{ 41 | image = img[i], 42 | patternSize = patternSize, 43 | corners = corners[i], 44 | patternWasFound = isFound 45 | } 46 | cv.imshow{"template", img[i]} 47 | cv.waitKey{0} 48 | end 49 | 50 | local objectPoints = {} 51 | 52 | for k = 1, numImages do 53 | objectPoints[k] = torch.FloatTensor(patternSize.height * patternSize.width, 1, 3) 54 | for i = 1, patternSize.height do 55 | for j = 1, patternSize.width do 56 | objectPoints[k][(i-1)*patternSize.width + j][1][1] = j; 57 | objectPoints[k][(i-1)*patternSize.width + j][1][2] = i; 58 | objectPoints[k][(i-1)*patternSize.width + j][1][3] = 0; 59 | end 60 | end 61 | end 62 | 63 | local error, cameraMatrix, distCoeffs, rvecs, tvecs = 64 | cv.calibrateCamera{ 65 | objectPoints = objectPoints, 66 | imagePoints = corners, 67 | imageSize = imageSize 68 | } 69 | 70 | print('Final re-projection error: '..error) 71 | 72 | local src = cv.imread{imagesPathPrefix..'image.jpg'} 73 | cv.imshow{"Photo to undistort", src} 74 | cv.waitKey{0} 75 | 76 | local dst = cv.undistort{src, cameraMatrix, distCoeffs} 77 | cv.imshow{"Photo to undistort", dst} 78 | cv.waitKey{0} 79 | -------------------------------------------------------------------------------- /include/cudawarping.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | extern "C" 6 | struct TensorWrapper remapCuda(struct cutorchInfo info, 7 | struct TensorWrapper src, struct TensorWrapper map1, 8 | struct TensorWrapper map2, int interpolation, struct TensorWrapper dst, 9 | int borderMode, struct ScalarWrapper borderValue); 10 | 11 | extern "C" 12 | struct TensorWrapper resizeCuda(struct cutorchInfo info, 13 | struct TensorWrapper src, struct TensorWrapper dst, 14 | struct SizeWrapper dsize, double fx, double fy, 15 | int interpolation); 16 | 17 | extern "C" 18 | struct TensorWrapper warpAffineCuda(struct cutorchInfo info, 19 | struct TensorWrapper src, struct TensorWrapper dst, 20 | struct TensorWrapper M, struct SizeWrapper dsize, 21 | int flags, int borderMode, struct ScalarWrapper borderValue); 22 | 23 | extern "C" 24 | struct TensorArray buildWarpAffineMapsCuda( 25 | struct cutorchInfo info, struct TensorWrapper M, bool inverse, 26 | struct SizeWrapper dsize, struct TensorWrapper xmap, struct TensorWrapper ymap); 27 | 28 | extern "C" 29 | struct TensorWrapper warpPerspectiveCuda(struct cutorchInfo info, 30 | struct TensorWrapper src, struct TensorWrapper dst, 31 | struct TensorWrapper M, struct SizeWrapper dsize, 32 | int flags, int borderMode, struct ScalarWrapper borderValue); 33 | 34 | extern "C" 35 | struct TensorArray buildWarpPerspectiveMapsCuda( 36 | struct cutorchInfo info, struct TensorWrapper M, bool inverse, 37 | struct SizeWrapper dsize, struct TensorWrapper xmap, struct TensorWrapper ymap); 38 | 39 | extern "C" 40 | struct TensorWrapper rotateCuda( 41 | struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst, 42 | struct SizeWrapper dsize, double angle, double xShift, double yShift, int interpolation); 43 | 44 | extern "C" 45 | struct TensorWrapper pyrDownCuda(struct cutorchInfo info, 46 | struct TensorWrapper src, struct TensorWrapper dst); 47 | 48 | extern "C" 49 | struct TensorWrapper pyrUpCuda(struct cutorchInfo info, 50 | struct TensorWrapper src, struct TensorWrapper dst); 51 | -------------------------------------------------------------------------------- /demo/cuda/optical_flow.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env luajit 2 | if not arg[1] or not arg[2] then 3 | print ('Usage: '..arg[0]..' image1.png image2.png') 4 | print ('ex: '..arg[0]..' ../data/basketball1.png ../data/basketball2.png') 5 | print ('Now using demo/data/basketball*.png') 6 | arg[1] = 'demo/data/basketball1.png' 7 | arg[2] = 'demo/data/basketball2.png' 8 | end 9 | 10 | local cv = require 'cv' 11 | require 'cv.cudaoptflow' 12 | require 'cv.imgcodecs' 13 | require 'cv.imgproc' 14 | require 'cv.highgui' 15 | require 'image' 16 | 17 | -- different method expect different range of values 18 | local flowMethods={ 19 | Brox ={computer=cv.cuda.BroxOpticalFlow{}, multiplier=1}, 20 | TVL1 ={computer=cv.cuda.OpticalFlowDual_TVL1{}, multiplier=1}, 21 | Farneback={computer=cv.cuda.FarnebackOpticalFlow{}, multiplier=255}, 22 | --LK=cv.cuda.DensePyrLKOpticalFlow{} -- LK require explicitly CV_8UC1 format which currently torch-opencv toGpuMat doesn't support 23 | } 24 | 25 | function alignUp(x, alignBoundary) 26 | alignBoundary=alignBoundary or 512 27 | require 'math' 28 | local rowBytes=x:size(x:dim())*x:elementSize() 29 | local strideBytes=math.ceil(rowBytes/alignBoundary)*alignBoundary 30 | return strideBytes/x:elementSize() 31 | end 32 | 33 | -- load images and copy into memory-aligned CudaTensor 34 | cpuImages={}; 35 | gpuImages={} 36 | 37 | for i=1, 2 do 38 | cpuImages[i]=cv.imread{arg[i], cv.IMREAD_GRAYSCALE} 39 | assert(cpuImages[i]:nDimension() > 0, 'Could not load '..arg[i]) 40 | 41 | cpuImages[i]=cpuImages[i]:float():div(255) 42 | local sizes=cpuImages[i]:size() 43 | local strides=torch.LongStorage{alignUp(cpuImages[i]), -1} 44 | gpuImages[i]=torch.CudaTensor(sizes, strides) 45 | gpuImages[i]:copy(cpuImages[i]) 46 | end 47 | 48 | -- perform optical flow calculation 49 | for key, flowMethod in pairs(flowMethods) do 50 | local flow = flowMethod.computer:calc{I0=gpuImages[1]*flowMethod.multiplier, I1=gpuImages[2]*flowMethod.multiplier}:float() 51 | local flowMag = torch.sqrt(torch.pow(flow, 2):sum(3)):squeeze() 52 | local flowAng = torch.atan2(flow:select(3, 1), flow:select(3, 2)) 53 | -- visualize flow using HSV 54 | -- color model ranges H:0-360, S:0-1, V:0-1 --> R:0-1, G:0-1, V:0-1 55 | local flowHSV=torch.cat({flowAng*180/math.pi+180, flowMag/flowMag:max(), torch.FloatTensor():ones(flowMag:size())}, 3) 56 | local flowRGB=(cv.cvtColor{src=flowHSV, code=cv.COLOR_HSV2RGB}*255):byte() 57 | cv.imshow{key, flowRGB} 58 | end 59 | cv.waitKey{0} 60 | -------------------------------------------------------------------------------- /include/optflow.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | namespace optflow = cv::optflow; 7 | namespace motempl = cv::motempl; 8 | 9 | extern "C" 10 | struct TensorWrapper calcOpticalFlowSF( 11 | struct TensorWrapper from, struct TensorWrapper to, struct TensorWrapper flow, 12 | int layers, int averaging_block_size, int max_flow); 13 | 14 | extern "C" 15 | struct TensorWrapper calcOpticalFlowSF_expanded( 16 | struct TensorWrapper from, struct TensorWrapper to, struct TensorWrapper flow, 17 | int layers, int averaging_block_size, int max_flow, 18 | double sigma_dist, double sigma_color, int postprocess_window, 19 | double sigma_dist_fix, double sigma_color_fix, double occ_thr, 20 | int upscale_averaging_radius, double upscale_sigma_dist, 21 | double upscale_sigma_color, double speed_up_thr); 22 | 23 | extern "C" 24 | struct TensorWrapper readOpticalFlow(const char *path); 25 | 26 | extern "C" 27 | bool writeOpticalFlow(const char *path, struct TensorWrapper flow); 28 | 29 | extern "C" 30 | void updateMotionHistory( 31 | struct TensorWrapper silhouette, struct TensorWrapper mhi, 32 | double timestamp, double duration); 33 | 34 | extern "C" 35 | struct TensorArray calcMotionGradient( 36 | struct TensorWrapper mhi, struct TensorWrapper mask, struct TensorWrapper orientation, 37 | double delta1, double delta2, int apertureSize); 38 | 39 | extern "C" 40 | double calcGlobalOrientation( 41 | struct TensorWrapper orientation, struct TensorWrapper mask, 42 | struct TensorWrapper mhi, double timestamp, double duration); 43 | 44 | extern "C" 45 | struct TensorPlusRectArray segmentMotion( 46 | struct TensorWrapper mhi, struct TensorWrapper segmask, 47 | double timestamp, double segThresh); 48 | 49 | extern "C" 50 | struct DenseOpticalFlowPtr createOptFlow_DeepFlow_optflow(); 51 | 52 | extern "C" 53 | struct DenseOpticalFlowPtr createOptFlow_SimpleFlow_optflow(); 54 | 55 | extern "C" 56 | struct DenseOpticalFlowPtr createOptFlow_Farneback_optflow(); 57 | 58 | #if CV_MAJOR_VERSION >= 3 && CV_MINOR_VERSION >= 1 59 | 60 | extern "C" 61 | struct TensorWrapper calcOpticalFlowSparseToDense( 62 | struct TensorWrapper from, struct TensorWrapper to, struct TensorWrapper flow, 63 | int grid_step, int k, float sigma, bool use_post_proc, float fgs_lambda, float fgs_sigma); 64 | 65 | extern "C" 66 | struct DenseOpticalFlowPtr createOptFlow_SparseToDense_optflow(); 67 | 68 | #endif 69 | -------------------------------------------------------------------------------- /include/videoio.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct VideoCapturePtr { 5 | void *ptr; 6 | 7 | inline cv::VideoCapture * operator->() { return static_cast(ptr); } 8 | inline VideoCapturePtr(cv::VideoCapture *ptr) { this->ptr = ptr; } 9 | inline cv::VideoCapture & operator*() { return *static_cast(this->ptr); } 10 | }; 11 | 12 | extern "C" 13 | struct VideoCapturePtr VideoCapture_ctor_default(); 14 | 15 | extern "C" 16 | struct VideoCapturePtr VideoCapture_ctor_device(int device); 17 | 18 | extern "C" 19 | struct VideoCapturePtr VideoCapture_ctor_filename(const char *filename); 20 | 21 | extern "C" 22 | void VideoCapture_dtor(VideoCapturePtr ptr); 23 | 24 | extern "C" 25 | bool VideoCapture_open(VideoCapturePtr ptr, int device); 26 | 27 | extern "C" 28 | bool VideoCapture_isOpened(VideoCapturePtr ptr); 29 | 30 | extern "C" 31 | void VideoCapture_release(VideoCapturePtr ptr); 32 | 33 | extern "C" 34 | bool VideoCapture_grab(VideoCapturePtr ptr); 35 | 36 | extern "C" 37 | struct TensorPlusBool VideoCapture_retrieve( 38 | VideoCapturePtr ptr, struct TensorWrapper image, int flag); 39 | 40 | extern "C" 41 | struct TensorPlusBool VideoCapture_read( 42 | VideoCapturePtr ptr, struct TensorWrapper image); 43 | 44 | extern "C" 45 | bool VideoCapture_set(VideoCapturePtr ptr, int propId, double value); 46 | 47 | extern "C" 48 | double VideoCapture_get(VideoCapturePtr ptr, int propId); 49 | 50 | struct VideoWriterPtr { 51 | void *ptr; 52 | 53 | inline cv::VideoWriter * operator->() { return static_cast(ptr); } 54 | inline VideoWriterPtr(cv::VideoWriter *ptr) { this->ptr = ptr; } 55 | inline cv::VideoWriter & operator*() { return *static_cast(this->ptr); } 56 | }; 57 | 58 | extern "C" 59 | struct VideoWriterPtr VideoWriter_ctor_default(); 60 | 61 | extern "C" 62 | struct VideoWriterPtr VideoWriter_ctor( 63 | const char *filename, int fourcc, double fps, struct SizeWrapper frameSize, bool isColor); 64 | 65 | extern "C" 66 | void VideoWriter_dtor(struct VideoWriterPtr ptr); 67 | 68 | extern "C" 69 | bool VideoWriter_open(struct VideoWriterPtr ptr, const char *filename, int fourcc, 70 | double fps, struct SizeWrapper frameSize, bool isColor); 71 | 72 | extern "C" 73 | bool VideoWriter_isOpened(struct VideoWriterPtr ptr); 74 | 75 | extern "C" 76 | void VideoWriter_release(struct VideoWriterPtr ptr); 77 | 78 | extern "C" 79 | void VideoWriter_write(struct VideoWriterPtr ptr, struct TensorWrapper image); 80 | 81 | extern "C" 82 | bool VideoWriter_set(VideoWriterPtr ptr, int propId, double value); 83 | 84 | extern "C" 85 | double VideoWriter_get(VideoWriterPtr ptr, int propId); 86 | 87 | extern "C" 88 | int VideoWriter_fourcc(char c1, char c2, char c3, char c4); -------------------------------------------------------------------------------- /cv/xphoto/init.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv._env' 2 | local ffi = require 'ffi' 3 | 4 | ffi.cdef[[ 5 | struct TensorWrapper xphoto_autowbGrayworld( 6 | struct TensorWrapper src, struct TensorWrapper dst, float thresh); 7 | 8 | struct TensorWrapper xphoto_balanceWhite( 9 | struct TensorWrapper src, struct TensorWrapper dst, int algorithmType, 10 | float inputMin, float inputMax, float outputMin, float outputMax); 11 | 12 | struct TensorWrapper xphoto_dctDenoising( 13 | struct TensorWrapper src, struct TensorWrapper dst, double sigma, int psize); 14 | 15 | struct TensorWrapper xphoto_inpaint( 16 | struct TensorWrapper src, struct TensorWrapper mask, 17 | struct TensorWrapper dst, int algorithmType); 18 | ]] 19 | 20 | local C = ffi.load(cv.libPath('xphoto')) 21 | 22 | cv.xphoto = {} 23 | 24 | cv.WHITE_BALANCE_SIMPLE = 0 25 | cv.WHITE_BALANCE_GRAYWORLD = 1 26 | cv.INPAINT_SHIFTMAP = 0 27 | 28 | function cv.xphoto.autowbGrayworld(t) 29 | local argRules = { 30 | {"src", required = true}, 31 | {"dst", default = nil}, 32 | {"thresh", default = 0.5} } 33 | local src, dst, thresh = cv.argcheck(t, argRules) 34 | return cv.unwrap_tensors( 35 | C.xphoto_autowbGrayworld( 36 | cv.wrap_tensor(src), cv.wrap_tensor(dst), thresh)) 37 | end 38 | 39 | function cv.xphoto.balanceWhite(t) 40 | local argRules = { 41 | {"src", required = true}, 42 | {"dst", default = nil}, 43 | {"algorithmType", required = true}, 44 | {"inputMin", default = 0}, 45 | {"inputMax", default = 255}, 46 | {"outputMin", default = 0}, 47 | {"outputMax", default = 255} } 48 | local src, dst, algorithmType, inputMin, inputMax, outputMin, outputMax = cv.argcheck(t, argRules) 49 | return cv.unwrap_tensors( 50 | C.xphoto_balanceWhite( 51 | cv.wrap_tensor(src), cv.wrap_tensor(dst), algorithmType, inputMin, inputMax, outputMin, outputMax)) 52 | end 53 | 54 | function cv.xphoto.dctDenoising(t) 55 | local argRules = { 56 | {"src", required = true}, 57 | {"dst", default = nil}, 58 | {"sigma", required = true}, 59 | {"psize", default = 16} } 60 | local src, dst, sigma, psize = cv.argcheck(t, argRules) 61 | return cv.unwrap_tensors( 62 | C.xphoto_dctDenoising(cv.wrap_tensor(src), cv.wrap_tensor(dst), sigma, psize) 63 | ) 64 | end 65 | 66 | function cv.xphoto.inpaint(t) 67 | local argRules = { 68 | {"src", required = true}, 69 | {"mask", required = true}, 70 | {"dst", default = nil}, 71 | {"algorithmType", required = true} } 72 | local src, mask, dst, algorithmType = cv.argcheck(t, argRules) 73 | return cv.unwrap_tensors( 74 | C.xphoto_inpaint( 75 | cv.wrap_tensor(src), cv.wrap_tensor(mask), 76 | cv.wrap_tensor(dst), algorithmType)) 77 | end -------------------------------------------------------------------------------- /include/cudafilters.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // Filter 6 | 7 | struct FilterPtr { 8 | void *ptr; 9 | inline cuda::Filter * operator->() { return static_cast(ptr); } 10 | inline FilterPtr(cuda::Filter *ptr) { this->ptr = ptr; } 11 | inline cuda::Filter & operator*() { return *static_cast(this->ptr); } 12 | }; 13 | 14 | extern "C" 15 | struct TensorWrapper Filter_applyCuda(struct cutorchInfo info, 16 | struct FilterPtr ptr, struct TensorWrapper src, struct TensorWrapper dst); 17 | 18 | extern "C" 19 | struct FilterPtr createBoxFilterCuda( 20 | int srcType, int dstType, struct SizeWrapper ksize, struct PointWrapper anchor, 21 | int borderMode, struct ScalarWrapper borderVal); 22 | 23 | extern "C" 24 | struct FilterPtr createLinearFilterCuda( 25 | int srcType, int dstType, struct TensorWrapper kernel, struct PointWrapper anchor, 26 | int borderMode, struct ScalarWrapper borderVal); 27 | 28 | extern "C" 29 | struct FilterPtr createLaplacianFilterCuda( 30 | int srcType, int dstType, int ksize, double scale, 31 | int borderMode, struct ScalarWrapper borderVal); 32 | 33 | extern "C" 34 | struct FilterPtr createSeparableLinearFilterCuda( 35 | int srcType, int dstType, struct TensorWrapper rowKernel, 36 | struct TensorWrapper columnKernel, struct PointWrapper anchor, 37 | int rowBorderMode, int columnBorderMode); 38 | 39 | extern "C" 40 | struct FilterPtr createDerivFilterCuda( 41 | int srcType, int dstType, int dx, int dy, int ksize, bool normalize, 42 | double scale, int rowBorderMode, int columnBorderMode); 43 | 44 | extern "C" 45 | struct FilterPtr createSobelFilterCuda( 46 | int srcType, int dstType, int dx, int dy, int ksize, 47 | double scale, int rowBorderMode, int columnBorderMode); 48 | 49 | extern "C" 50 | struct FilterPtr createScharrFilterCuda( 51 | int srcType, int dstType, int dx, int dy, 52 | double scale, int rowBorderMode, int columnBorderMode); 53 | 54 | extern "C" 55 | struct FilterPtr createGaussianFilterCuda( 56 | int srcType, int dstType, struct SizeWrapper ksize, 57 | double sigma1, double sigma2, int rowBorderMode, int columnBorderMode); 58 | 59 | extern "C" 60 | struct FilterPtr createMorphologyFilterCuda( 61 | int op, int srcType, struct TensorWrapper kernel, 62 | struct PointWrapper anchor, int iterations); 63 | 64 | extern "C" 65 | struct FilterPtr createBoxMaxFilterCuda( 66 | int srcType, struct SizeWrapper ksize, struct PointWrapper anchor, 67 | int borderMode, struct ScalarWrapper borderVal); 68 | 69 | extern "C" 70 | struct FilterPtr createBoxMinFilterCuda( 71 | int srcType, struct SizeWrapper ksize, struct PointWrapper anchor, 72 | int borderMode, struct ScalarWrapper borderVal); 73 | 74 | extern "C" 75 | struct FilterPtr createRowSumFilterCuda( 76 | int srcType, int dstType, int ksize, int anchor, 77 | int borderMode, struct ScalarWrapper borderVal); 78 | 79 | extern "C" 80 | struct FilterPtr createColumnSumFilterCuda( 81 | int srcType, int dstType, int ksize, int anchor, 82 | int borderMode, struct ScalarWrapper borderVal); 83 | -------------------------------------------------------------------------------- /include/Classes.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | // This is cv::Ptr with all fields made public 5 | // TODO I hope a safer solution to be here one day 6 | template 7 | struct PublicPtr 8 | { 9 | public: 10 | cv::detail::PtrOwner* owner; 11 | T* stored; 12 | }; 13 | 14 | // increfs a cv::Ptr and returns the pointer 15 | template 16 | T *rescueObjectFromPtr(cv::Ptr ptr) { 17 | PublicPtr *publicPtr = reinterpret_cast *>(&ptr); 18 | publicPtr->owner->incRef(); 19 | return ptr.get(); 20 | } 21 | 22 | // FileNode 23 | 24 | struct FileNodePtr { 25 | void *ptr; 26 | 27 | inline cv::FileNode * operator->() { return static_cast(ptr); } 28 | inline FileNodePtr(cv::FileNode *ptr) { this->ptr = ptr; } 29 | inline cv::FileNode & operator*() { return *static_cast(this->ptr); } 30 | }; 31 | 32 | extern "C" 33 | struct FileNodePtr FileNode_ctor(); 34 | 35 | extern "C" 36 | void FileNode_dtor(FileNodePtr ptr); 37 | 38 | // FileStorage 39 | 40 | struct FileStoragePtr { 41 | void *ptr; 42 | 43 | inline cv::FileStorage * operator->() { return static_cast(ptr); } 44 | inline FileStoragePtr(cv::FileStorage *ptr) { this->ptr = ptr; } 45 | inline cv::FileStorage & operator*() { return *static_cast(this->ptr); } 46 | }; 47 | 48 | extern "C" 49 | struct FileStoragePtr FileStorage_ctor_default(); 50 | 51 | extern "C" 52 | struct FileStoragePtr FileStorage_ctor(const char *source, int flags, const char *encoding); 53 | 54 | extern "C" 55 | void FileStorage_dtor(FileStoragePtr ptr); 56 | 57 | extern "C" 58 | bool FileStorage_open(FileStoragePtr ptr, const char *filename, int flags, const char *encoding); 59 | 60 | extern "C" 61 | bool FileStorage_isOpened(FileStoragePtr ptr); 62 | 63 | extern "C" 64 | void FileStorage_release(FileStoragePtr ptr); 65 | 66 | extern "C" 67 | const char *FileStorage_releaseAndGetString(FileStoragePtr ptr); 68 | 69 | // Algorithm 70 | 71 | struct AlgorithmPtr { 72 | void *ptr; 73 | 74 | inline cv::Algorithm * operator->() { return static_cast(ptr); } 75 | inline AlgorithmPtr(cv::Algorithm *ptr) { this->ptr = ptr; } 76 | }; 77 | 78 | extern "C" 79 | struct AlgorithmPtr Algorithm_ctor(); 80 | 81 | extern "C" 82 | void Algorithm_dtor(AlgorithmPtr ptr); 83 | 84 | extern "C" 85 | void Algorithm_clear(AlgorithmPtr ptr); 86 | 87 | extern "C" 88 | void Algorithm_write(AlgorithmPtr ptr, FileStoragePtr fileStorage); 89 | 90 | extern "C" 91 | void Algorithm_read(AlgorithmPtr ptr, FileNodePtr fileNode); 92 | 93 | extern "C" 94 | bool Algorithm_empty(AlgorithmPtr ptr); 95 | 96 | extern "C" 97 | void Algorithm_save(AlgorithmPtr ptr, const char *filename); 98 | 99 | extern "C" 100 | const char *Algorithm_getDefaultName(AlgorithmPtr ptr); 101 | 102 | // cv::Ptr 103 | 104 | struct CvPtrPtr { 105 | void *ptr; 106 | 107 | inline cv::Ptr * operator->() { return static_cast *>(ptr); } 108 | inline CvPtrPtr(cv::Ptr *ptr) { this->ptr = ptr; } 109 | inline cv::Ptr & operator*() { return *static_cast *>(this->ptr); } 110 | }; 111 | 112 | extern "C" 113 | void CvPtr_dtor(struct CvPtrPtr ptr) 114 | { 115 | delete static_cast *>(ptr.ptr); 116 | } 117 | -------------------------------------------------------------------------------- /src/highgui.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | extern "C" 4 | void imshow(const char *winname, struct TensorWrapper image) 5 | { 6 | cv::imshow(winname, image.toMat()); 7 | } 8 | 9 | extern "C" 10 | int waitKey(int delay) 11 | { 12 | return cv::waitKey(delay); 13 | } 14 | 15 | extern "C" 16 | void namedWindow(const char *winname, int flags) 17 | { 18 | cv::namedWindow(winname, flags); 19 | } 20 | 21 | extern "C" 22 | void destroyWindow(const char *winname) 23 | { 24 | cv::destroyWindow(winname); 25 | } 26 | 27 | extern "C" 28 | void destroyAllWindows() 29 | { 30 | cv::destroyAllWindows(); 31 | } 32 | 33 | extern "C" 34 | int startWindowThread() 35 | { 36 | return cv::startWindowThread(); 37 | } 38 | 39 | extern "C" 40 | void resizeWindow(const char *winname, int width, int height) 41 | { 42 | cv::resizeWindow(winname, width, height); 43 | } 44 | 45 | extern "C" 46 | void moveWindow(const char *winname, int x, int y) 47 | { 48 | cv::moveWindow(winname, x, y); 49 | } 50 | 51 | extern "C" 52 | void setWindowProperty(const char *winname, int prop_id, double prop_value) 53 | { 54 | cv::setWindowProperty(winname, prop_id, prop_value); 55 | } 56 | 57 | extern "C" 58 | void setWindowTitle(const char *winname, const char *title) 59 | { 60 | cv::setWindowTitle(winname, title); 61 | } 62 | 63 | extern "C" 64 | double getWindowProperty(const char *winname, int prop_id) 65 | { 66 | return cv::getWindowProperty(winname, prop_id); 67 | } 68 | 69 | extern "C" 70 | void setMouseCallback(const char *winname, cv::MouseCallback onMouse, void *userdata) 71 | { 72 | cv::setMouseCallback(winname, onMouse, userdata); 73 | } 74 | 75 | extern "C" 76 | int getMouseWheelData(int flags) 77 | { 78 | return cv::getMouseWheelDelta(flags); 79 | } 80 | 81 | extern "C" 82 | int createTrackbar( 83 | const char *trackbarname, const char *winname, int *value, 84 | int count, cv::TrackbarCallback onChange, void *userdata) 85 | { 86 | return cv::createTrackbar(trackbarname, winname, value, count, onChange, userdata); 87 | } 88 | 89 | extern "C" 90 | int getTrackbarPos(const char *trackbarname, const char *winname) 91 | { 92 | return cv::getTrackbarPos(trackbarname, winname); 93 | } 94 | 95 | extern "C" 96 | void setTrackbarPos(const char *trackbarname, const char *winname, int pos) 97 | { 98 | cv::setTrackbarPos(trackbarname, winname, pos); 99 | } 100 | 101 | extern "C" 102 | void setTrackbarMax(const char *trackbarname, const char *winname, int maxval) 103 | { 104 | cv::setTrackbarMax(trackbarname, winname, maxval); 105 | } 106 | 107 | extern "C" 108 | void updateWindow(const char *winname) 109 | { 110 | cv::updateWindow(winname); 111 | } 112 | 113 | extern "C" 114 | void displayOverlay(const char *winname, const char *text, int delayms) 115 | { 116 | cv::displayOverlay(winname, text, delayms); 117 | } 118 | 119 | extern "C" 120 | void displayStatusBar(const char *winname, const char *text, int delayms) 121 | { 122 | cv::displayStatusBar(winname, text, delayms); 123 | } 124 | 125 | extern "C" 126 | void saveWindowParameters(const char *windowName) 127 | { 128 | cv::saveWindowParameters(windowName); 129 | } 130 | 131 | extern "C" 132 | void loadWindowParameters(const char *windowName) 133 | { 134 | cv::loadWindowParameters(windowName); 135 | } 136 | 137 | int createButton(const char *bar_name, cv::ButtonCallback on_change, 138 | void* userdata, int type, bool initial_button_state) 139 | { 140 | return cv::createButton(bar_name, on_change, userdata, type, initial_button_state); 141 | } 142 | -------------------------------------------------------------------------------- /cv/Classes.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv._env' 2 | local ffi = require 'ffi' 3 | 4 | ffi.cdef[[ 5 | struct PtrWrapper { 6 | void *ptr; 7 | }; 8 | ]] 9 | 10 | local C = ffi.load(cv.libPath('Classes')) 11 | 12 | -- ***** FileNode ***** 13 | 14 | ffi.cdef[[ 15 | struct PtrWrapper FileNode_ctor(); 16 | 17 | void FileNode_dtor(struct PtrWrapper ptr); 18 | ]] 19 | 20 | do 21 | local FileNode = torch.class('cv.FileNode', cv) 22 | 23 | function FileNode:__init() 24 | self.ptr = ffi.gc(C.FileNode_ctor(), C.FileNode_dtor) 25 | end 26 | end 27 | 28 | -- ***** FileStorage ***** 29 | 30 | ffi.cdef[[ 31 | struct PtrWrapper FileStorage_ctor(const char *source, int flags, const char *encoding); 32 | 33 | struct PtrWrapper FileStorage_ctor_default(); 34 | 35 | void FileStorage_dtor(struct PtrWrapper ptr); 36 | 37 | bool FileStorage_open(struct PtrWrapper ptr, const char *filename, int flags, const char *encoding); 38 | 39 | bool FileStorage_isOpened(struct PtrWrapper ptr); 40 | 41 | void FileStorage_release(struct PtrWrapper ptr); 42 | 43 | const char *FileStorage_releaseAndGetString(struct PtrWrapper ptr); 44 | ]] 45 | 46 | do 47 | local FileStorage = torch.class('cv.FileStorage', cv) 48 | 49 | function FileStorage:__init(t) 50 | local source = t.source 51 | local flags = t.flags 52 | local encoding = t.encoding or '' 53 | 54 | if source and flags then 55 | self.ptr = ffi.gc(C.FileStorage_ctor(source, flags, encoding), C.FileStorage_dtor) 56 | else 57 | self.ptr = ffi.gc(C.FileStorage_ctor_default(), C.FileStorage_dtor) 58 | end 59 | end 60 | 61 | function FileStorage:open(t) 62 | local source = assert(t.source) 63 | local flags = assert(t.flags) 64 | local encoding = t.encoding or '' 65 | 66 | return C.FileStorage_open(self.ptr, source, flags, encoding) 67 | end 68 | 69 | function FileStorage:isOpened() 70 | return C.FileStorage_isOpened(self.ptr) 71 | end 72 | 73 | function FileStorage:release() 74 | C.FileStorage_release(self.ptr) 75 | end 76 | 77 | function FileStorage:releaseAndGetString() 78 | return ffi.string(C.FileStorage_releaseAndGetString(self.ptr)) 79 | end 80 | end 81 | 82 | -- ***** Algorithm ***** 83 | 84 | ffi.cdef[[ 85 | struct PtrWrapper Algorithm_ctor(); 86 | 87 | void Algorithm_dtor(struct PtrWrapper ptr); 88 | 89 | void Algorithm_clear(struct PtrWrapper ptr); 90 | 91 | void Algorithm_write(struct PtrWrapper ptr, struct PtrWrapper fileStorage); 92 | 93 | void Algorithm_read(struct PtrWrapper ptr, struct PtrWrapper fileNode); 94 | 95 | bool Algorithm_empty(struct PtrWrapper ptr); 96 | 97 | void Algorithm_save(struct PtrWrapper ptr, const char *filename); 98 | 99 | const char *Algorithm_getDefaultName(struct PtrWrapper ptr); 100 | ]] 101 | 102 | do 103 | local Algorithm = torch.class('cv.Algorithm', cv) 104 | 105 | function Algorithm:__init() 106 | self.ptr = ffi.gc(C.Algorithm_ctor(), C.Algorithm_dtor) 107 | end 108 | 109 | function Algorithm:clear() 110 | C.Algorithm_clear(self.ptr) 111 | end 112 | 113 | function Algorithm:write(fileStorage) 114 | C.Algorithm_write(self.ptr, fileStorage.ptr) 115 | end 116 | 117 | function Algorithm:read(fileNode) 118 | C.Algorithm_read(self.ptr, fileNode.ptr) 119 | end 120 | 121 | function Algorithm:empty() 122 | return C.Algorithm_empty(self.ptr) 123 | end 124 | 125 | function Algorithm:save(filename) 126 | C.Algorithm_save(self.ptr, filename) 127 | end 128 | 129 | function Algorithm:getDefaultName() 130 | return ffi.string(C.Algorithm_getDefaultName(self.ptr)) 131 | end 132 | end 133 | 134 | -- cv::Ptr<> 135 | 136 | ffi.cdef[[ 137 | void CvPtr_dtor(struct PtrWrapper ptr); 138 | ]] 139 | 140 | return cv 141 | -------------------------------------------------------------------------------- /src/videoio.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /****************** Classes ******************/ 4 | 5 | // VideoCapture 6 | 7 | extern "C" 8 | struct VideoCapturePtr VideoCapture_ctor_default() 9 | { 10 | return new cv::VideoCapture(); 11 | } 12 | 13 | extern "C" 14 | struct VideoCapturePtr VideoCapture_ctor_device(int device) 15 | { 16 | return new cv::VideoCapture(device); 17 | } 18 | 19 | extern "C" 20 | struct VideoCapturePtr VideoCapture_ctor_filename(const char *filename) 21 | { 22 | return new cv::VideoCapture(filename); 23 | } 24 | 25 | extern "C" 26 | void VideoCapture_dtor(VideoCapturePtr ptr) 27 | { 28 | delete static_cast(ptr.ptr); 29 | } 30 | 31 | extern "C" 32 | bool VideoCapture_open(VideoCapturePtr ptr, int device) 33 | { 34 | return ptr->open(device); 35 | } 36 | 37 | extern "C" 38 | bool VideoCapture_isOpened(VideoCapturePtr ptr) 39 | { 40 | return ptr->isOpened(); 41 | } 42 | 43 | extern "C" 44 | void VideoCapture_release(VideoCapturePtr ptr) 45 | { 46 | ptr->release(); 47 | } 48 | 49 | extern "C" 50 | bool VideoCapture_grab(VideoCapturePtr ptr) 51 | { 52 | return ptr->grab(); 53 | } 54 | 55 | extern "C" 56 | struct TensorPlusBool VideoCapture_retrieve( 57 | VideoCapturePtr ptr, struct TensorWrapper image, int flag) 58 | { 59 | TensorPlusBool retval; 60 | MatT result = image.toMatT(); 61 | retval.val = ptr->retrieve(result, flag); 62 | new (&retval.tensor) TensorWrapper(result); 63 | return retval; 64 | } 65 | 66 | extern "C" 67 | struct TensorPlusBool VideoCapture_read( 68 | VideoCapturePtr ptr, struct TensorWrapper image) 69 | { 70 | TensorPlusBool retval; 71 | MatT result = image.toMatT(); 72 | // See #77 73 | if (ptr->grab()) { 74 | ptr->retrieve(result); 75 | retval.val = true; 76 | } else { 77 | retval.val = false; 78 | } 79 | new (&retval.tensor) TensorWrapper(result); 80 | return retval; 81 | } 82 | 83 | extern "C" 84 | bool VideoCapture_set(VideoCapturePtr ptr, int propId, double value) 85 | { 86 | return ptr->set(propId, value); 87 | } 88 | 89 | extern "C" 90 | double VideoCapture_get(VideoCapturePtr ptr, int propId) 91 | { 92 | return ptr->get(propId); 93 | } 94 | 95 | // VideoWriter 96 | 97 | extern "C" 98 | struct VideoWriterPtr VideoWriter_ctor_default() 99 | { 100 | return new cv::VideoWriter(); 101 | } 102 | 103 | extern "C" 104 | struct VideoWriterPtr VideoWriter_ctor( 105 | const char *filename, int fourcc, double fps, struct SizeWrapper frameSize, bool isColor) 106 | { 107 | return new cv::VideoWriter(filename, fourcc, fps, frameSize, isColor); 108 | } 109 | 110 | extern "C" 111 | void VideoWriter_dtor(struct VideoWriterPtr ptr) 112 | { 113 | delete static_cast(ptr.ptr); 114 | } 115 | 116 | extern "C" 117 | bool VideoWriter_open(struct VideoWriterPtr ptr, const char *filename, int fourcc, 118 | double fps, struct SizeWrapper frameSize, bool isColor) 119 | { 120 | return ptr->open(filename, fourcc, fps, frameSize, isColor); 121 | } 122 | 123 | extern "C" 124 | bool VideoWriter_isOpened(struct VideoWriterPtr ptr) 125 | { 126 | return ptr->isOpened(); 127 | } 128 | 129 | extern "C" 130 | void VideoWriter_release(struct VideoWriterPtr ptr) 131 | { 132 | ptr->release(); 133 | } 134 | 135 | extern "C" 136 | void VideoWriter_write(struct VideoWriterPtr ptr, struct TensorWrapper image) 137 | { 138 | ptr->write(image.toMat()); 139 | } 140 | 141 | extern "C" 142 | bool VideoWriter_set(VideoWriterPtr ptr, int propId, double value) 143 | { 144 | return ptr->set(propId, value); 145 | } 146 | 147 | extern "C" 148 | double VideoWriter_get(VideoWriterPtr ptr, int propId) 149 | { 150 | return ptr->get(propId); 151 | } 152 | 153 | extern "C" 154 | int VideoWriter_fourcc(char c1, char c2, char c3, char c4) 155 | { 156 | return cv::VideoWriter::fourcc(c1, c2, c3, c4); 157 | } 158 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(Torch_OpenCV) 2 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR) 3 | 4 | OPTION(BUILD_TESTS "Build C tests" OFF) 5 | OPTION(WITH_CUDA "Wrap CUDA packages" ON ) 6 | 7 | IF (DEFINED ENV{WITH_CUDA}) 8 | SET(WITH_CUDA $ENV{WITH_CUDA}) 9 | ENDIF() 10 | 11 | SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") 12 | 13 | SET(OPENCV_MODULES_TO_WRAP 14 | core imgcodecs highgui features2d flann imgproc ml optflow photo superres videoio video 15 | objdetect calib3d ximgproc stitching xphoto) 16 | 17 | IF (WITH_CUDA) 18 | SET(OPENCV_MODULES_TO_WRAP ${OPENCV_MODULES_TO_WRAP} cudaarithm cudacodec cudawarping 19 | cudafilters cudaoptflow cudabgsegm cudafeatures2d cudaimgproc cudastereo cudaobjdetect) 20 | ENDIF() 21 | 22 | IF (DEFINED ENV{DONT_WRAP}) 23 | SET(DONT_WRAP $ENV{DONT_WRAP}) 24 | ENDIF() 25 | 26 | IF (DONT_WRAP) 27 | LIST(REMOVE_ITEM OPENCV_MODULES_TO_WRAP ${DONT_WRAP}) 28 | ENDIF() 29 | 30 | # Unfortunately, OpenCVConfig.cmake doesn't make use of FIND_PACKAGE's "OPTIONAL_COMPONENTS" 31 | # So let's invoke FIND_PACKAGE twice: 32 | 33 | # Once (error-throwing) to check if OpenCV is present 34 | FIND_PACKAGE(OpenCV 3.1 EXACT REQUIRED) 35 | # Once more (silently) to look for the installed modules 36 | FIND_PACKAGE(OpenCV 3.1 EXACT QUIET OPTIONAL_COMPONENTS ${OPENCV_MODULES_TO_WRAP}) 37 | 38 | IF(LUAROCKS_PREFIX) 39 | MESSAGE(STATUS "Installing Torch through Luarocks") 40 | STRING(REGEX REPLACE "(.*)lib/luarocks/rocks.*" "\\1" CMAKE_INSTALL_PREFIX "${LUAROCKS_PREFIX}") 41 | MESSAGE(STATUS "Prefix inferred from Luarocks: ${CMAKE_INSTALL_PREFIX}") 42 | ENDIF() 43 | 44 | FIND_PACKAGE(Torch REQUIRED) 45 | INCLUDE_DIRECTORIES(${Torch_INSTALL_INCLUDE} ${OpenCV_INCLUDE_DIRS}) 46 | 47 | # See #78 48 | IF (APPLE) 49 | SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -stdlib=libc++") 50 | ENDIF() 51 | 52 | SET(CXX_STANDARD_REQUIRED ON) 53 | SET(CMAKE_CXX_STANDARD 11) 54 | 55 | # See #90 56 | IF (CMAKE_VERSION VERSION_LESS 3.1) 57 | SET(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -std=c++11) 58 | ENDIF() 59 | 60 | FILE(GLOB luasrc *.lua cv/*.lua) 61 | SET(luasrc ${luasrc}) 62 | ADD_TORCH_PACKAGE(cv "" "${luasrc}" "cv") 63 | 64 | # Check if both OpenCV CUDA interface and cutorch are installed 65 | IF (WITH_CUDA) 66 | IF (NOT OPENCV_CUDAARITHM_FOUND) 67 | MESSAGE(WARNING "WITH_CUDA is ON, but OpenCV CUDA interface wasn't found. Won't build OpenCV-CUDA wrappers.") 68 | SET(WITH_CUDA OFF) 69 | ELSEIF(NOT EXISTS "${Torch_INSTALL_INCLUDE}/THC/") 70 | MESSAGE(WARNING "WITH_CUDA is ON, but cutorch wasn't found. Won't build OpenCV-CUDA wrappers") 71 | SET(WITH_CUDA OFF) 72 | ENDIF() 73 | ENDIF() 74 | 75 | IF (WITH_CUDA) 76 | FIND_PACKAGE(CUDA REQUIRED) 77 | 78 | INCLUDE_DIRECTORIES(${CUDA_INCLUDE_DIRS}) 79 | ADD_DEFINITIONS(-DWITH_CUDA) 80 | ENDIF() 81 | 82 | SET(SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/src") 83 | INCLUDE_DIRECTORIES("${CMAKE_CURRENT_SOURCE_DIR}/include") 84 | 85 | ADD_LIBRARY(Common SHARED "${SOURCE_DIR}/Common.cpp") 86 | TARGET_LINK_LIBRARIES(Common TH ${OpenCV_LIBS}) 87 | 88 | ADD_LIBRARY(Classes SHARED "${SOURCE_DIR}/Classes.cpp") 89 | TARGET_LINK_LIBRARIES(Classes Common) 90 | 91 | IF (WITH_CUDA) 92 | ADD_LIBRARY(CUDACommon SHARED "${SOURCE_DIR}/CUDACommon.cpp") 93 | TARGET_LINK_LIBRARIES(CUDACommon Common THC ${CUDA_LIBRARIES}) 94 | ENDIF() 95 | 96 | # The main loop. For each module check if it's present; if yes, add its wrappers to targets 97 | 98 | FOREACH(MODULE ${OPENCV_MODULES_TO_WRAP}) 99 | STRING(TOUPPER ${MODULE} MODULE_UPPERCASE) 100 | IF (OPENCV_${MODULE_UPPERCASE}_FOUND) 101 | IF (${MODULE_UPPERCASE} MATCHES "^CUDA") 102 | IF (WITH_CUDA) 103 | ADD_SUBDIRECTORY(cv/${MODULE}) 104 | ADD_LIBRARY(${MODULE} SHARED "${SOURCE_DIR}/${MODULE}.cpp") 105 | TARGET_LINK_LIBRARIES(${MODULE} CUDACommon) 106 | ENDIF() 107 | ELSE() 108 | ADD_SUBDIRECTORY(cv/${MODULE}) 109 | ADD_LIBRARY(${MODULE} SHARED "${SOURCE_DIR}/${MODULE}.cpp") 110 | TARGET_LINK_LIBRARIES(${MODULE} Common) 111 | ENDIF() 112 | 113 | SET(RESULTING_MODULES_LIST "${MODULE}, ${RESULTING_MODULES_LIST}") 114 | ENDIF() 115 | ENDFOREACH() 116 | 117 | MESSAGE(STATUS "Modules to wrap: ${RESULTING_MODULES_LIST}") 118 | 119 | INSTALL(DIRECTORY "${CMAKE_BINARY_DIR}/lib" DESTINATION "${Torch_INSTALL_LUA_PATH_SUBDIR}/cv") 120 | 121 | IF (BUILD_TESTS) 122 | FILE(GLOB Tests_SRC "${SOURCE_DIR}/tests/*.cpp") 123 | ADD_LIBRARY(Tests SHARED ${Tests_SRC}) 124 | TARGET_LINK_LIBRARIES(Tests Common) 125 | ENDIF() 126 | -------------------------------------------------------------------------------- /src/optflow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | extern "C" 4 | struct TensorWrapper calcOpticalFlowSF( 5 | struct TensorWrapper from, struct TensorWrapper to, struct TensorWrapper flow, 6 | int layers, int averaging_block_size, int max_flow) 7 | { 8 | MatT flow_mat = flow.toMatT(); 9 | optflow::calcOpticalFlowSF( 10 | from.toMat(), to.toMat(), flow_mat, layers, averaging_block_size, max_flow); 11 | return TensorWrapper(flow_mat); 12 | } 13 | 14 | extern "C" 15 | struct TensorWrapper calcOpticalFlowSF_expanded( 16 | struct TensorWrapper from, struct TensorWrapper to, struct TensorWrapper flow, 17 | int layers, int averaging_block_size, int max_flow, 18 | double sigma_dist, double sigma_color, int postprocess_window, 19 | double sigma_dist_fix, double sigma_color_fix, double occ_thr, 20 | int upscale_averaging_radius, double upscale_sigma_dist, 21 | double upscale_sigma_color, double speed_up_thr) 22 | { 23 | MatT flow_mat = flow.toMatT(); 24 | optflow::calcOpticalFlowSF( 25 | from.toMat(), to.toMat(), flow_mat, layers, averaging_block_size, 26 | max_flow, sigma_dist, sigma_color, postprocess_window, sigma_dist_fix, 27 | sigma_color_fix, occ_thr, upscale_averaging_radius, 28 | upscale_sigma_dist, upscale_sigma_color, speed_up_thr); 29 | return TensorWrapper(flow_mat); 30 | } 31 | 32 | extern "C" 33 | struct TensorWrapper readOpticalFlow(const char *path) 34 | { 35 | return TensorWrapper(MatT(optflow::readOpticalFlow(path))); 36 | } 37 | 38 | extern "C" 39 | bool writeOpticalFlow(const char *path, struct TensorWrapper flow) 40 | { 41 | return optflow::writeOpticalFlow(path, flow.toMat()); 42 | } 43 | 44 | extern "C" 45 | void updateMotionHistory( 46 | struct TensorWrapper silhouette, struct TensorWrapper mhi, 47 | double timestamp, double duration) 48 | { 49 | motempl::updateMotionHistory(silhouette.toMat(), mhi.toMat(), timestamp, duration); 50 | } 51 | 52 | extern "C" 53 | struct TensorArray calcMotionGradient( 54 | struct TensorWrapper mhi, struct TensorWrapper mask, struct TensorWrapper orientation, 55 | double delta1, double delta2, int apertureSize) 56 | { 57 | std::vector retval(2); 58 | retval[0] = mask.toMatT(); 59 | retval[1] = orientation.toMatT(); 60 | motempl::calcMotionGradient(mhi.toMat(), retval[0], retval[1], delta1, delta2, apertureSize); 61 | return TensorArray(retval); 62 | } 63 | 64 | extern "C" 65 | double calcGlobalOrientation( 66 | struct TensorWrapper orientation, struct TensorWrapper mask, 67 | struct TensorWrapper mhi, double timestamp, double duration) 68 | { 69 | return motempl::calcGlobalOrientation( 70 | orientation.toMat(), mask.toMat(), mhi.toMat(), timestamp, duration); 71 | } 72 | 73 | extern "C" 74 | struct TensorPlusRectArray segmentMotion( 75 | struct TensorWrapper mhi, struct TensorWrapper segmask, 76 | double timestamp, double segThresh) 77 | { 78 | struct TensorPlusRectArray retval; 79 | std::vector rects; 80 | 81 | MatT segmask_mat = segmask.toMatT(); 82 | motempl::segmentMotion(mhi.toMat(), segmask_mat, rects, timestamp, segThresh); 83 | new(&retval.tensor) TensorWrapper(segmask_mat); 84 | new (&retval.rects) RectArray(rects); 85 | return retval; 86 | } 87 | 88 | // DenseOpticalFlowPtr is from video.hpp 89 | 90 | extern "C" 91 | struct DenseOpticalFlowPtr createOptFlow_DeepFlow_optflow() 92 | { 93 | return rescueObjectFromPtr(optflow::createOptFlow_DeepFlow()); 94 | } 95 | 96 | extern "C" 97 | struct DenseOpticalFlowPtr createOptFlow_SimpleFlow_optflow() 98 | { 99 | return rescueObjectFromPtr(optflow::createOptFlow_SimpleFlow()); 100 | } 101 | 102 | extern "C" 103 | struct DenseOpticalFlowPtr createOptFlow_Farneback_optflow() 104 | { 105 | return rescueObjectFromPtr(optflow::createOptFlow_Farneback()); 106 | } 107 | 108 | #if CV_MAJOR_VERSION >= 3 && CV_MINOR_VERSION >= 1 109 | 110 | extern "C" 111 | struct TensorWrapper calcOpticalFlowSparseToDense( 112 | struct TensorWrapper from, struct TensorWrapper to, struct TensorWrapper flow, 113 | int grid_step, int k, float sigma, bool use_post_proc, float fgs_lambda, float fgs_sigma) 114 | { 115 | MatT flow_mat = flow.toMatT(); 116 | optflow::calcOpticalFlowSparseToDense( 117 | from.toMat(), to.toMat(), flow_mat, grid_step, k, 118 | sigma, use_post_proc, fgs_lambda, fgs_sigma); 119 | return TensorWrapper(flow_mat); 120 | } 121 | 122 | extern "C" 123 | struct DenseOpticalFlowPtr createOptFlow_SparseToDense_optflow() 124 | { 125 | return rescueObjectFromPtr(optflow::createOptFlow_SparseToDense()); 126 | } 127 | 128 | #endif 129 | -------------------------------------------------------------------------------- /include/cudaarithm.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct LookUpTablePtr { 6 | void *ptr; 7 | 8 | inline cuda::LookUpTable * operator->() { return static_cast(ptr); } 9 | inline LookUpTablePtr(cuda::LookUpTable *ptr) { this->ptr = ptr; } 10 | inline operator const cuda::LookUpTable &() { return *static_cast(ptr); } 11 | }; 12 | 13 | struct ConvolutionPtr { 14 | void *ptr; 15 | 16 | inline cuda::Convolution * operator->() { return static_cast(ptr); } 17 | inline ConvolutionPtr(cuda::Convolution *ptr) { this->ptr = ptr; } 18 | inline operator const cuda::Convolution &() { return *static_cast(ptr); } 19 | }; 20 | 21 | extern "C" 22 | struct TensorWrapper minCuda( 23 | struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst); 24 | 25 | extern "C" 26 | struct TensorWrapper maxCuda( 27 | struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst); 28 | 29 | extern "C" 30 | struct TensorPlusDouble thresholdCuda( 31 | struct cutorchInfo info, struct TensorWrapper src, 32 | struct TensorWrapper dst, double thresh, double maxval, int type); 33 | 34 | extern "C" 35 | struct TensorWrapper magnitudeCuda( 36 | struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude); 37 | 38 | extern "C" 39 | struct TensorWrapper magnitudeSqrCuda( 40 | struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude); 41 | 42 | extern "C" 43 | struct TensorWrapper magnitude2Cuda( 44 | struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitude); 45 | 46 | extern "C" 47 | struct TensorWrapper magnitudeSqr2Cuda( 48 | struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitudeSqr); 49 | 50 | extern "C" 51 | struct TensorWrapper phaseCuda( 52 | struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, 53 | struct TensorWrapper angle, bool angleInDegrees); 54 | 55 | extern "C" 56 | struct TensorArray cartToPolarCuda( 57 | struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, 58 | struct TensorWrapper magnitude, struct TensorWrapper angle, bool angleInDegrees); 59 | 60 | extern "C" 61 | struct TensorArray polarToCartCuda( 62 | struct cutorchInfo info, struct TensorWrapper magnitude, struct TensorWrapper angle, 63 | struct TensorWrapper x, struct TensorWrapper y, bool angleInDegrees); 64 | 65 | extern "C" 66 | struct LookUpTablePtr LookUpTable_ctorCuda( 67 | struct cutorchInfo info, struct TensorWrapper lut); 68 | 69 | extern "C" 70 | struct TensorWrapper LookUpTable_transformCuda( 71 | struct cutorchInfo info, struct LookUpTablePtr ptr, 72 | struct TensorWrapper src, struct TensorWrapper dst); 73 | 74 | extern "C" 75 | struct TensorWrapper rectStdDevCuda( 76 | struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sqr, 77 | struct TensorWrapper dst, struct RectWrapper rect); 78 | 79 | extern "C" 80 | struct TensorWrapper normalizeCuda( 81 | struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst, 82 | double alpha, double beta, int norm_type, int dtype, struct TensorWrapper mask); 83 | 84 | extern "C" 85 | struct TensorWrapper integralCuda( 86 | struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum); 87 | 88 | extern "C" 89 | struct TensorWrapper sqrIntegralCuda( 90 | struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum); 91 | 92 | extern "C" 93 | struct TensorWrapper mulSpectrumsCuda( 94 | struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, 95 | struct TensorWrapper dst, int flags, bool conjB); 96 | 97 | extern "C" 98 | struct TensorWrapper mulAndScaleSpectrumsCuda( 99 | struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, 100 | struct TensorWrapper dst, int flags, float scale, bool conjB); 101 | 102 | extern "C" 103 | struct TensorWrapper dftCuda( 104 | struct cutorchInfo info, struct TensorWrapper src, 105 | struct TensorWrapper dst, struct SizeWrapper dft_size, int flags); 106 | 107 | extern "C" 108 | struct ConvolutionPtr Convolution_ctorCuda( 109 | struct cutorchInfo info, struct SizeWrapper user_block_size); 110 | 111 | extern "C" 112 | struct TensorWrapper Convolution_convolveCuda( 113 | struct cutorchInfo info, struct ConvolutionPtr ptr, struct TensorWrapper image, 114 | struct TensorWrapper templ, struct TensorWrapper result, bool ccor); -------------------------------------------------------------------------------- /src/flann.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Various IndexParams 4 | 5 | extern "C" 6 | void IndexParams_dtor(struct IndexParamsPtr ptr) 7 | { 8 | delete static_cast(ptr.ptr); 9 | } 10 | 11 | extern "C" 12 | struct KDTreeIndexParamsPtr KDTreeIndexParams_ctor(int trees) 13 | { 14 | return new flann::KDTreeIndexParams(trees); 15 | } 16 | 17 | extern "C" 18 | struct LinearIndexParamsPtr LinearIndexParams_ctor() 19 | { 20 | return new flann::LinearIndexParams(); 21 | } 22 | 23 | extern "C" 24 | struct CompositeIndexParamsPtr CompositeIndexParams_ctor( 25 | int trees, int branching, int iterations, 26 | cvflann::flann_centers_init_t centers_init, float cb_index) 27 | { 28 | return new flann::CompositeIndexParams( 29 | trees, branching, iterations, centers_init, cb_index); 30 | } 31 | 32 | extern "C" 33 | struct AutotunedIndexParamsPtr AutotunedIndexParams_ctor( 34 | float target_precision, float build_weight, 35 | float memory_weight, float sample_fraction) 36 | { 37 | return new flann::AutotunedIndexParams( 38 | target_precision, build_weight, memory_weight, sample_fraction); 39 | } 40 | 41 | extern "C" 42 | struct HierarchicalClusteringIndexParamsPtr HierarchicalClusteringIndexParams_ctor( 43 | int branching, cvflann::flann_centers_init_t centers_init, int trees, int leaf_size) 44 | { 45 | return new flann::HierarchicalClusteringIndexParams( 46 | branching, centers_init, trees, leaf_size); 47 | } 48 | 49 | extern "C" 50 | struct KMeansIndexParamsPtr KMeansIndexParams_ctor( 51 | int branching, int iterations, cvflann::flann_centers_init_t centers_init, float cb_index) 52 | { 53 | return new flann::KMeansIndexParams(branching, iterations, centers_init, cb_index); 54 | } 55 | 56 | extern "C" 57 | struct LshIndexParamsPtr LshIndexParams_ctor( 58 | int table_number, int key_size, int multi_probe_level) 59 | { 60 | return new flann::LshIndexParams(table_number, key_size, multi_probe_level); 61 | } 62 | 63 | extern "C" 64 | struct SavedIndexParamsPtr SavedIndexParams_ctor(const char *filename) 65 | { 66 | return new flann::SavedIndexParams(filename); 67 | } 68 | 69 | extern "C" 70 | struct SearchParamsPtr SearchParams_ctor(int checks, float eps, bool sorted) 71 | { 72 | return new flann::SearchParams(checks, eps, sorted); 73 | } 74 | 75 | // Index 76 | 77 | extern "C" 78 | struct IndexPtr Index_ctor_default() 79 | { 80 | return new flann::Index(); 81 | } 82 | 83 | extern "C" 84 | struct IndexPtr Index_ctor( 85 | struct TensorWrapper features, struct IndexParamsPtr params, 86 | cvflann::flann_distance_t distType) 87 | { 88 | return new flann::Index(features.toMat(), params, distType); 89 | } 90 | 91 | extern "C" 92 | void Index_dtor(struct IndexPtr ptr) 93 | { 94 | delete static_cast(ptr.ptr); 95 | } 96 | 97 | extern "C" 98 | void Index_build( 99 | struct IndexPtr ptr, struct TensorWrapper features, 100 | struct IndexParamsPtr params, cvflann::flann_distance_t distType) 101 | { 102 | ptr->build(features.toMat(), params, distType); 103 | } 104 | 105 | extern "C" 106 | struct TensorArray Index_knnSearch( 107 | struct IndexPtr ptr, struct TensorWrapper query, int knn, struct TensorWrapper indices, 108 | struct TensorWrapper dists, struct SearchParamsPtr params) 109 | { 110 | std::vector retval(2); 111 | retval[0] = indices.toMatT(); 112 | retval[1] = dists.toMatT(); 113 | 114 | ptr->knnSearch(query.toMat(), retval[0], retval[1], knn, params); 115 | 116 | return TensorArray(retval); 117 | } 118 | 119 | extern "C" 120 | struct TensorArrayPlusInt Index_radiusSearch( 121 | struct IndexPtr ptr, struct TensorWrapper query, double radius, int maxResults, 122 | struct TensorWrapper indices, struct TensorWrapper dists, struct SearchParamsPtr params) 123 | { 124 | struct TensorArrayPlusInt retval; 125 | 126 | std::vector result(2); 127 | result[0] = indices.toMatT(); 128 | result[1] = dists.toMatT(); 129 | 130 | retval.val = ptr->radiusSearch( 131 | query.toMat(), result[0], result[1], radius, maxResults, params); 132 | 133 | new (&retval.tensors) TensorArray(result); 134 | 135 | return retval; 136 | } 137 | 138 | extern "C" 139 | void Index_save(struct IndexPtr ptr, const char *filename) 140 | { 141 | ptr->save(filename); 142 | } 143 | 144 | extern "C" 145 | bool Index_load(struct IndexPtr ptr, struct TensorWrapper features, const char *filename) 146 | { 147 | return ptr->load(features.toMat(), filename); 148 | } 149 | 150 | extern "C" 151 | void Index_release(struct IndexPtr ptr) 152 | { 153 | ptr->release(); 154 | } 155 | 156 | extern "C" 157 | int Index_getDistance(struct IndexPtr ptr) 158 | { 159 | return ptr->getDistance(); 160 | } 161 | 162 | extern "C" 163 | int Index_getAlgorithm(struct IndexPtr ptr) 164 | { 165 | return ptr->getAlgorithm(); 166 | } 167 | -------------------------------------------------------------------------------- /include/CUDACommon.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace cuda = cv::cuda; 5 | 6 | #define CV_CUDA 66 7 | 8 | // Kill "destination" and assign "source" data to it. 9 | // "destination" is always supposed to be an empty Tensor 10 | extern "C" 11 | void transfer_tensor_CUDA(THCState *state, THCudaTensor *dst, struct TensorWrapper srcWrapper); 12 | 13 | struct cutorchInfo { 14 | int deviceID; 15 | THCState *state; 16 | }; 17 | 18 | /**************** A custom allocator that uses Torch memory management for Mats ****************/ 19 | 20 | class TorchCompatibleAllocator: public cuda::GpuMat::Allocator { 21 | public: 22 | THCState *cutorchState; 23 | 24 | bool allocate(cuda::GpuMat* mat, int rows, int cols, size_t elemSize); 25 | void free(cuda::GpuMat* mat); 26 | }; 27 | 28 | extern "C" 29 | void initAllocatorCUDA(cutorchInfo info); 30 | 31 | /****************************************** GpuMatT ********************************************/ 32 | 33 | class GpuMatT { 34 | public: 35 | cuda::GpuMat mat; 36 | // The Tensor that `mat` was created from, or nullptr 37 | THCudaTensor *tensor; 38 | 39 | inline operator cv::_InputOutputArray() { return this->mat; } 40 | 41 | GpuMatT(cuda::GpuMat &&mat); 42 | 43 | GpuMatT(cuda::GpuMat &mat); 44 | 45 | GpuMatT(); 46 | }; 47 | 48 | GpuMatT TensorWrapper::toGpuMatT() { 49 | GpuMatT retval; 50 | 51 | if (this->isNull()) { 52 | retval.tensor = nullptr; 53 | } else { 54 | retval.mat = this->toGpuMat(); 55 | retval.tensor = reinterpret_cast(this->tensorPtr); 56 | } 57 | 58 | return retval; 59 | } 60 | 61 | /************* Fake "custom memory stack impl for OpenCV" to use cutorch streams *************/ 62 | 63 | // Description below 64 | class FakeMemoryPool; 65 | class FakeMemoryStack; 66 | class FakeStackAllocator; 67 | class FakeStreamImpl; 68 | class FakeStream; 69 | 70 | class FakeMemoryStack { 71 | public: 72 | unsigned char* datastart; 73 | unsigned char* dataend; 74 | unsigned char* tip; 75 | 76 | bool isFree; 77 | FakeMemoryPool* pool; 78 | 79 | #if !defined(NDEBUG) 80 | std::vector allocations; 81 | #endif 82 | 83 | unsigned char* requestMemory(size_t size); 84 | void returnMemory(unsigned char* ptr); 85 | }; 86 | 87 | class FakeMemoryPool { 88 | public: 89 | cv::Mutex mtx_; 90 | 91 | bool initialized_; 92 | size_t stackSize_; 93 | int stackCount_; 94 | 95 | unsigned char* mem_; 96 | 97 | std::vector stacks_; 98 | 99 | void initilizeImpl(); 100 | void release(); 101 | FakeMemoryStack* getFreeMemStack(); 102 | }; 103 | 104 | void FakeMemoryPool::release() { 105 | if (mem_) { 106 | #if !defined(NDEBUG) 107 | for (int i = 0; i < stackCount_; ++i) { 108 | CV_DbgAssert( stacks_[i].isFree ); 109 | CV_DbgAssert( stacks_[i].tip == stacks_[i].datastart ); 110 | } 111 | #endif 112 | 113 | cudaFree(mem_); 114 | mem_ = 0; 115 | initialized_ = false; 116 | } 117 | } 118 | 119 | class FakeStream { 120 | public: 121 | cv::Ptr impl_; 122 | 123 | FakeStream() {} 124 | FakeStream(cv::Ptr & impl): impl_(impl) {} 125 | }; 126 | 127 | class FakeDefaultDeviceInitializer { 128 | public: 129 | FakeDefaultDeviceInitializer(); 130 | ~FakeDefaultDeviceInitializer(); 131 | 132 | FakeStream & getNullStream(int deviceId); 133 | FakeMemoryPool* getMemoryPool(int deviceId); 134 | 135 | private: 136 | void initStreams(); 137 | void initPools(); 138 | 139 | std::vector> streams_; 140 | cv::Mutex streams_mtx_; 141 | 142 | std::vector pools_; 143 | cv::Mutex pools_mtx_; 144 | }; 145 | 146 | class FakeStackAllocator : public cuda::GpuMat::Allocator { 147 | public: 148 | cudaStream_t stream_; 149 | FakeMemoryStack *memStack_; 150 | size_t alignment_; 151 | 152 | FakeStackAllocator(cudaStream_t stream); 153 | bool allocate(cuda::GpuMat* mat, int rows, int cols, size_t elemSize); 154 | void free(cuda::GpuMat* mat); 155 | }; 156 | 157 | class FakeStreamImpl { 158 | public: 159 | cudaStream_t stream; 160 | bool ownStream; 161 | 162 | cv::Ptr stackAllocator; 163 | 164 | FakeStreamImpl(cudaStream_t stream_) : stream(stream_), ownStream(false) { 165 | stackAllocator = cv::makePtr(stream); 166 | } 167 | }; 168 | 169 | /* Whenever we call an OpenCV-CUDA function from Lua, it's necessary 170 | * to tell OpenCV which device and stream are currently in use by cutorch. 171 | * For this, a single `cv::cuda::Stream` (in form of `FakeStream`) object 172 | * is stored. When invoking an OpenCV function, we refresh that object 173 | * and pass through a reference to it. */ 174 | 175 | // Here that object is: 176 | FakeStream fakeStream; 177 | 178 | // Here is the function that updates and returns it: 179 | cuda::Stream & prepareStream(cutorchInfo info); 180 | -------------------------------------------------------------------------------- /src/cudafilters.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | extern "C" 4 | struct TensorWrapper Filter_applyCuda(cutorchInfo info, 5 | struct FilterPtr ptr, struct TensorWrapper src, struct TensorWrapper dst) 6 | { 7 | cuda::GpuMat retval = dst.toGpuMat(); 8 | ptr->apply(src.toGpuMat(), retval, prepareStream(info)); 9 | return TensorWrapper(retval, info.state); 10 | } 11 | 12 | extern "C" 13 | struct FilterPtr createBoxFilterCuda( 14 | int srcType, int dstType, struct SizeWrapper ksize, struct PointWrapper anchor, 15 | int borderMode, struct ScalarWrapper borderVal) 16 | { 17 | return rescueObjectFromPtr(cuda::createBoxFilter( 18 | srcType, dstType, ksize, anchor, borderMode, borderVal)); 19 | } 20 | 21 | extern "C" 22 | struct FilterPtr createLinearFilterCuda( 23 | int srcType, int dstType, struct TensorWrapper kernel, struct PointWrapper anchor, 24 | int borderMode, struct ScalarWrapper borderVal) 25 | { 26 | return rescueObjectFromPtr(cuda::createLinearFilter( 27 | srcType, dstType, kernel.toMat(), anchor, borderMode, borderVal)); 28 | } 29 | 30 | extern "C" 31 | struct FilterPtr createLaplacianFilterCuda( 32 | int srcType, int dstType, int ksize, double scale, 33 | int borderMode, struct ScalarWrapper borderVal) 34 | { 35 | return rescueObjectFromPtr(cuda::createLaplacianFilter( 36 | srcType, dstType, ksize, scale, borderMode, borderVal)); 37 | } 38 | 39 | extern "C" 40 | struct FilterPtr createSeparableLinearFilterCuda( 41 | int srcType, int dstType, struct TensorWrapper rowKernel, 42 | struct TensorWrapper columnKernel, struct PointWrapper anchor, 43 | int rowBorderMode, int columnBorderMode) 44 | { 45 | return rescueObjectFromPtr(cuda::createSeparableLinearFilter( 46 | srcType, dstType, rowKernel.toMat(), columnKernel.toMat(), anchor, 47 | rowBorderMode, columnBorderMode)); 48 | } 49 | 50 | extern "C" 51 | struct FilterPtr createDerivFilterCuda( 52 | int srcType, int dstType, int dx, int dy, int ksize, bool normalize, 53 | double scale, int rowBorderMode, int columnBorderMode) 54 | { 55 | return rescueObjectFromPtr(cuda::createDerivFilter( 56 | srcType, dstType, dx, dy, ksize, normalize, scale, rowBorderMode, columnBorderMode)); 57 | } 58 | 59 | extern "C" 60 | struct FilterPtr createSobelFilterCuda( 61 | int srcType, int dstType, int dx, int dy, int ksize, 62 | double scale, int rowBorderMode, int columnBorderMode) 63 | { 64 | return rescueObjectFromPtr(cuda::createSobelFilter( 65 | srcType, dstType, dx, dy, ksize, scale, rowBorderMode, columnBorderMode)); 66 | } 67 | 68 | extern "C" 69 | struct FilterPtr createScharrFilterCuda( 70 | int srcType, int dstType, int dx, int dy, 71 | double scale, int rowBorderMode, int columnBorderMode) 72 | { 73 | return rescueObjectFromPtr(cuda::createScharrFilter( 74 | srcType, dstType, dx, dy, scale, rowBorderMode, columnBorderMode)); 75 | } 76 | 77 | extern "C" 78 | struct FilterPtr createGaussianFilterCuda( 79 | int srcType, int dstType, struct SizeWrapper ksize, 80 | double sigma1, double sigma2, int rowBorderMode, int columnBorderMode) 81 | { 82 | return rescueObjectFromPtr(cuda::createGaussianFilter( 83 | srcType, dstType, ksize, sigma1, sigma2, rowBorderMode, columnBorderMode)); 84 | } 85 | 86 | extern "C" 87 | struct FilterPtr createMorphologyFilterCuda( 88 | int op, int srcType, struct TensorWrapper kernel, 89 | struct PointWrapper anchor, int iterations) 90 | { 91 | return rescueObjectFromPtr(cuda::createMorphologyFilter( 92 | op, srcType, kernel.toMat(), anchor, iterations)); 93 | } 94 | 95 | extern "C" 96 | struct FilterPtr createBoxMaxFilterCuda( 97 | int srcType, struct SizeWrapper ksize, struct PointWrapper anchor, 98 | int borderMode, struct ScalarWrapper borderVal) 99 | { 100 | return rescueObjectFromPtr(cuda::createBoxMaxFilter( 101 | srcType, ksize, anchor, borderMode, borderVal)); 102 | } 103 | 104 | extern "C" 105 | struct FilterPtr createBoxMinFilterCuda( 106 | int srcType, struct SizeWrapper ksize, struct PointWrapper anchor, 107 | int borderMode, struct ScalarWrapper borderVal) 108 | { 109 | return rescueObjectFromPtr(cuda::createBoxMaxFilter( 110 | srcType, ksize, anchor, borderMode, borderVal)); 111 | } 112 | 113 | extern "C" 114 | struct FilterPtr createRowSumFilterCuda( 115 | int srcType, int dstType, int ksize, int anchor, 116 | int borderMode, struct ScalarWrapper borderVal) 117 | { 118 | return rescueObjectFromPtr(cuda::createRowSumFilter( 119 | srcType, dstType, ksize, anchor, borderMode, borderVal)); 120 | } 121 | 122 | extern "C" 123 | struct FilterPtr createColumnSumFilterCuda( 124 | int srcType, int dstType, int ksize, int anchor, 125 | int borderMode, struct ScalarWrapper borderVal) 126 | { 127 | return rescueObjectFromPtr(cuda::createColumnSumFilter( 128 | srcType, dstType, ksize, anchor, borderMode, borderVal)); 129 | } 130 | -------------------------------------------------------------------------------- /include/cudaobjdetect.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // HOG 6 | 7 | struct HOGPtr { 8 | void *ptr; 9 | inline cuda::HOG * operator->() { return static_cast(ptr); } 10 | inline HOGPtr(cuda::HOG *ptr) { this->ptr = ptr; } 11 | inline cuda::HOG & operator*() { return *static_cast(this->ptr); } 12 | }; 13 | 14 | // CascadeClassifier 15 | 16 | struct CascadeClassifierPtr { 17 | void *ptr; 18 | inline cuda::CascadeClassifier * operator->() { return static_cast(ptr); } 19 | inline CascadeClassifierPtr(cuda::CascadeClassifier *ptr) { this->ptr = ptr; } 20 | inline cuda::CascadeClassifier & operator*() { return *static_cast(this->ptr); } 21 | }; 22 | 23 | extern "C" 24 | struct HOGPtr HOG_ctorCuda( 25 | struct SizeWrapper win_size, struct SizeWrapper block_size, 26 | struct SizeWrapper block_stride, struct SizeWrapper cell_size, int nbins); 27 | 28 | extern "C" 29 | void HOG_setWinSigmaCuda(struct HOGPtr ptr, double val); 30 | 31 | extern "C" 32 | double HOG_getWinSigmaCuda(struct HOGPtr ptr); 33 | 34 | extern "C" 35 | void HOG_setL2HysThresholdCuda(struct HOGPtr ptr, double val); 36 | 37 | extern "C" 38 | double HOG_getL2HysThresholdCuda(struct HOGPtr ptr); 39 | 40 | extern "C" 41 | void HOG_setGammaCorrectionCuda(struct HOGPtr ptr, bool val); 42 | 43 | extern "C" 44 | bool HOG_getGammaCorrectionCuda(struct HOGPtr ptr); 45 | 46 | extern "C" 47 | void HOG_setNumLevelsCuda(struct HOGPtr ptr, int val); 48 | 49 | extern "C" 50 | int HOG_getNumLevelsCuda(struct HOGPtr ptr); 51 | 52 | extern "C" 53 | void HOG_setHitThresholdCuda(struct HOGPtr ptr, double val); 54 | 55 | extern "C" 56 | double HOG_getHitThresholdCuda(struct HOGPtr ptr); 57 | 58 | extern "C" 59 | void HOG_setWinStrideCuda(struct HOGPtr ptr, struct SizeWrapper val); 60 | 61 | extern "C" 62 | struct SizeWrapper HOG_getWinStrideCuda(struct HOGPtr ptr); 63 | 64 | extern "C" 65 | void HOG_setScaleFactorCuda(struct HOGPtr ptr, double val); 66 | 67 | extern "C" 68 | double HOG_getScaleFactorCuda(struct HOGPtr ptr); 69 | 70 | extern "C" 71 | void HOG_setGroupThresholdCuda(struct HOGPtr ptr, int val); 72 | 73 | extern "C" 74 | int HOG_getGroupThresholdCuda(struct HOGPtr ptr); 75 | 76 | extern "C" 77 | void HOG_setDescriptorFormatCuda(struct HOGPtr ptr, int val); 78 | 79 | extern "C" 80 | int HOG_getDescriptorFormatCuda(struct HOGPtr ptr); 81 | 82 | extern "C" 83 | size_t HOG_getDescriptorSizeCuda(struct HOGPtr ptr); 84 | 85 | extern "C" 86 | size_t HOG_getBlockHistogramSizeCuda(struct HOGPtr ptr); 87 | 88 | extern "C" 89 | void HOG_setSVMDetectorCuda(struct HOGPtr ptr, struct TensorWrapper val); 90 | 91 | extern "C" 92 | struct TensorWrapper HOG_getDefaultPeopleDetectorCuda(struct HOGPtr ptr); 93 | 94 | extern "C" 95 | struct TensorPlusPointArray HOG_detectCuda( 96 | struct cutorchInfo info, struct HOGPtr ptr, struct TensorWrapper img); 97 | 98 | extern "C" 99 | struct TensorPlusRectArray HOG_detectMultiScaleCuda( 100 | struct cutorchInfo info, struct HOGPtr ptr, struct TensorWrapper img); 101 | 102 | extern "C" 103 | struct TensorWrapper HOG_computeCuda( 104 | struct cutorchInfo info, struct HOGPtr ptr, struct TensorWrapper img, 105 | struct TensorWrapper descriptors); 106 | 107 | extern "C" 108 | struct CascadeClassifierPtr CascadeClassifier_ctor_filenameCuda(const char *filename); 109 | 110 | extern "C" 111 | struct CascadeClassifierPtr CascadeClassifier_ctor_fileCuda(struct FileStoragePtr file); 112 | 113 | extern "C" 114 | void CascadeClassifier_setMaxObjectSizeCuda(struct CascadeClassifierPtr ptr, struct SizeWrapper val); 115 | 116 | extern "C" 117 | struct SizeWrapper CascadeClassifier_getMaxObjectSizeCuda(struct CascadeClassifierPtr ptr); 118 | 119 | extern "C" 120 | void CascadeClassifier_setMinObjectSizeCuda(struct CascadeClassifierPtr ptr, struct SizeWrapper val); 121 | 122 | extern "C" 123 | struct SizeWrapper CascadeClassifier_getMinObjectSizeCuda(struct CascadeClassifierPtr ptr); 124 | 125 | extern "C" 126 | void CascadeClassifier_setScaleFactorCuda(struct CascadeClassifierPtr ptr, double val); 127 | 128 | extern "C" 129 | double CascadeClassifier_getScaleFactorCuda(struct CascadeClassifierPtr ptr); 130 | 131 | extern "C" 132 | void CascadeClassifier_setMinNeighborsCuda(struct CascadeClassifierPtr ptr, int val); 133 | 134 | extern "C" 135 | int CascadeClassifier_getMinNeighborsCuda(struct CascadeClassifierPtr ptr); 136 | 137 | extern "C" 138 | void CascadeClassifier_setFindLargestObjectCuda(struct CascadeClassifierPtr ptr, bool val); 139 | 140 | extern "C" 141 | bool CascadeClassifier_getFindLargestObjectCuda(struct CascadeClassifierPtr ptr); 142 | 143 | extern "C" 144 | void CascadeClassifier_setMaxNumObjectsCuda(struct CascadeClassifierPtr ptr, int val); 145 | 146 | extern "C" 147 | int CascadeClassifier_getMaxNumObjectsCuda(struct CascadeClassifierPtr ptr); 148 | 149 | extern "C" 150 | struct SizeWrapper CascadeClassifier_getClassifierSizeCuda(struct CascadeClassifierPtr ptr); 151 | 152 | extern "C" 153 | struct TensorWrapper CascadeClassifier_detectMultiScaleCuda( 154 | struct cutorchInfo info, struct CascadeClassifierPtr ptr, 155 | struct TensorWrapper image, struct TensorWrapper objects); 156 | 157 | extern "C" 158 | struct RectArray CascadeClassifier_convertCuda( 159 | struct CascadeClassifierPtr ptr, struct TensorWrapper gpu_objects); 160 | -------------------------------------------------------------------------------- /include/cudaimgproc.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // CornernessCriteria 6 | 7 | struct CornernessCriteriaPtr { 8 | void *ptr; 9 | inline cuda::CornernessCriteria * operator->() { return static_cast(ptr); } 10 | inline CornernessCriteriaPtr(cuda::CornernessCriteria *ptr) { this->ptr = ptr; } 11 | inline cuda::CornernessCriteria & operator*() { return *static_cast(this->ptr); } 12 | }; 13 | 14 | // CornersDetector 15 | 16 | struct CornersDetectorPtr { 17 | void *ptr; 18 | inline cuda::CornersDetector * operator->() { return static_cast(ptr); } 19 | inline CornersDetectorPtr(cuda::CornersDetector *ptr) { this->ptr = ptr; } 20 | inline cuda::CornersDetector & operator*() { return *static_cast(this->ptr); } 21 | }; 22 | 23 | // TemplateMatching 24 | 25 | struct TemplateMatchingPtr { 26 | void *ptr; 27 | inline cuda::TemplateMatching * operator->() { return static_cast(ptr); } 28 | inline TemplateMatchingPtr(cuda::TemplateMatching *ptr) { this->ptr = ptr; } 29 | inline cuda::TemplateMatching & operator*() { return *static_cast(this->ptr); } 30 | }; 31 | 32 | extern "C" 33 | struct TensorWrapper cvtColorCuda(struct cutorchInfo info, 34 | struct TensorWrapper src, struct TensorWrapper dst, int code, int dstCn); 35 | 36 | extern "C" 37 | struct TensorWrapper demosaicingCuda(struct cutorchInfo info, 38 | struct TensorWrapper src, struct TensorWrapper dst, int code, int dcn); 39 | 40 | extern "C" 41 | void swapChannelsCuda( 42 | struct cutorchInfo info, struct TensorWrapper image, 43 | struct Vec4iWrapper dstOrder); 44 | 45 | extern "C" 46 | struct TensorWrapper gammaCorrectionCuda(struct cutorchInfo info, 47 | struct TensorWrapper src, struct TensorWrapper dst, bool forward); 48 | 49 | extern "C" 50 | struct TensorWrapper alphaCompCuda(struct cutorchInfo info, 51 | struct TensorWrapper img1, struct TensorWrapper img2, 52 | struct TensorWrapper dst, int alpha_op); 53 | 54 | extern "C" 55 | struct TensorWrapper calcHistCuda( 56 | struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper hist); 57 | 58 | extern "C" 59 | struct TensorWrapper equalizeHistCuda(struct cutorchInfo info, 60 | struct TensorWrapper src, struct TensorWrapper dst); 61 | 62 | extern "C" 63 | struct TensorWrapper evenLevelsCuda(struct cutorchInfo info, 64 | struct TensorWrapper levels, int nLevels, int lowerLevel, int upperLevel); 65 | 66 | extern "C" 67 | struct TensorWrapper histEvenCuda(struct cutorchInfo info, 68 | struct TensorWrapper src, struct TensorWrapper hist, 69 | int histSize, int lowerLevel, int upperLevel); 70 | 71 | extern "C" 72 | struct TensorArray histEven_4Cuda(struct cutorchInfo info, 73 | struct TensorWrapper src, struct TensorArray hist, struct TensorWrapper histSize, 74 | struct TensorWrapper lowerLevel, struct TensorWrapper upperLevel); 75 | 76 | extern "C" 77 | struct TensorWrapper histRangeCuda(struct cutorchInfo info, 78 | struct TensorWrapper src, struct TensorWrapper hist, 79 | struct TensorWrapper levels); 80 | 81 | extern "C" 82 | struct TensorArray histRange_4Cuda(struct cutorchInfo info, 83 | struct TensorWrapper src, struct TensorArray hist, struct TensorWrapper levels); 84 | 85 | extern "C" 86 | struct CornernessCriteriaPtr createHarrisCornerCuda( 87 | int srcType, int blockSize, int ksize, double k, int borderType); 88 | 89 | extern "C" 90 | struct CornernessCriteriaPtr createMinEigenValCornerCuda( 91 | int srcType, int blockSize, int ksize, int borderType); 92 | 93 | extern "C" 94 | struct TensorWrapper CornernessCriteria_computeCuda( 95 | struct cutorchInfo info, struct CornernessCriteriaPtr ptr, 96 | struct TensorWrapper src, struct TensorWrapper dst); 97 | 98 | extern "C" 99 | struct CornersDetectorPtr createGoodFeaturesToTrackDetectorCuda( 100 | int srcType, int maxCorners, double qualityLevel, double minDistance, 101 | int blockSize, bool useHarrisDetector, double harrisK); 102 | 103 | extern "C" 104 | struct TensorWrapper CornersDetector_detectCuda( 105 | struct cutorchInfo info, struct CornersDetectorPtr ptr, struct TensorWrapper image, 106 | struct TensorWrapper corners, struct TensorWrapper mask); 107 | 108 | extern "C" 109 | struct TemplateMatchingPtr createTemplateMatchingCuda( 110 | int srcType, int method, struct SizeWrapper user_block_size); 111 | 112 | extern "C" 113 | struct TensorWrapper TemplateMatching_matchCuda( 114 | struct cutorchInfo info, struct TemplateMatchingPtr ptr, struct TensorWrapper image, 115 | struct TensorWrapper templ, struct TensorWrapper result); 116 | 117 | extern "C" 118 | struct TensorWrapper bilateralFilterCuda(struct cutorchInfo info, 119 | struct TensorWrapper src, struct TensorWrapper dst, int kernel_size, 120 | float sigma_color, float sigma_spatial, int borderMode); 121 | 122 | extern "C" 123 | struct TensorWrapper blendLinearCuda(struct cutorchInfo info, 124 | struct TensorWrapper img1, struct TensorWrapper img2, struct TensorWrapper weights1, 125 | struct TensorWrapper weights2, struct TensorWrapper result); -------------------------------------------------------------------------------- /include/objdetect.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct BaseCascadeClassifierPtr { 6 | void *ptr; 7 | 8 | inline cv::BaseCascadeClassifier * operator->() { return static_cast(ptr); } 9 | inline BaseCascadeClassifierPtr(cv::BaseCascadeClassifier *ptr) { this->ptr = ptr; } 10 | inline cv::BaseCascadeClassifier & operator*() { return *static_cast(this->ptr); } 11 | }; 12 | 13 | struct CascadeClassifierPtr { 14 | void *ptr; 15 | 16 | inline cv::CascadeClassifier * operator->() { return static_cast(ptr); } 17 | inline CascadeClassifierPtr(cv::CascadeClassifier *ptr) { this->ptr = ptr; } 18 | inline cv::CascadeClassifier & operator*() { return *static_cast(this->ptr); } 19 | }; 20 | 21 | struct HOGDescriptorPtr { 22 | void *ptr; 23 | 24 | inline cv::HOGDescriptor * operator->() { return static_cast(ptr); } 25 | inline HOGDescriptorPtr(cv::HOGDescriptor *ptr) { this->ptr = ptr; } 26 | inline cv::HOGDescriptor & operator*() { return *static_cast(this->ptr); } 27 | }; 28 | 29 | extern "C" 30 | struct TensorPlusRectArray groupRectangles(struct RectArray rectList, int groupThreshold, double eps); 31 | 32 | extern "C" 33 | bool BaseCascadeClassifier_empty(struct BaseCascadeClassifierPtr ptr); 34 | 35 | extern "C" 36 | bool BaseCascadeClassifier_load(struct BaseCascadeClassifierPtr ptr, const char *filename); 37 | 38 | extern "C" 39 | bool BaseCascadeClassifier_isOldFormatCascade(struct BaseCascadeClassifierPtr ptr); 40 | 41 | extern "C" 42 | struct SizeWrapper BaseCascadeClassifier_getOriginalWindowSize(struct BaseCascadeClassifierPtr ptr); 43 | 44 | extern "C" 45 | int BaseCascadeClassifier_getFeatureType(struct BaseCascadeClassifierPtr ptr); 46 | 47 | extern "C" 48 | struct CascadeClassifierPtr CascadeClassifier_ctor_default(); 49 | 50 | extern "C" 51 | struct CascadeClassifierPtr CascadeClassifier_ctor(const char *filename); 52 | 53 | extern "C" 54 | void CascadeClassifier_dtor(struct CascadeClassifierPtr ptr); 55 | 56 | extern "C" 57 | bool CascadeClassifier_read(struct CascadeClassifierPtr ptr, struct FileNodePtr node); 58 | 59 | extern "C" 60 | struct RectArray CascadeClassifier_detectMultiScale(struct CascadeClassifierPtr ptr, 61 | struct TensorWrapper image, double scaleFactor, int minNeighbors, int flags, 62 | struct SizeWrapper minSize, struct SizeWrapper maxSize); 63 | 64 | extern "C" 65 | struct TensorPlusRectArray CascadeClassifier_detectMultiScale2(struct CascadeClassifierPtr ptr, 66 | struct TensorWrapper image, double scaleFactor, int minNeighbors, int flags, 67 | struct SizeWrapper minSize, struct SizeWrapper maxSize); 68 | 69 | extern "C" 70 | struct TensorArrayPlusRectArray CascadeClassifier_detectMultiScale3( 71 | struct CascadeClassifierPtr ptr, struct TensorWrapper image, double scaleFactor, 72 | int minNeighbors, int flags, struct SizeWrapper minSize, struct SizeWrapper maxSize, 73 | bool outputRejectLevels); 74 | 75 | extern "C" 76 | bool CascadeClassifier_convert( 77 | struct CascadeClassifierPtr ptr, const char *oldcascade, const char *newcascade); 78 | 79 | extern "C" 80 | struct HOGDescriptorPtr HOGDescriptor_ctor( 81 | struct SizeWrapper winSize, struct SizeWrapper blockSize, struct SizeWrapper blockStride, 82 | struct SizeWrapper cellSize, int nbins, int derivAperture, double winSigma, 83 | int histogramNormType, double L2HysThreshold, bool gammaCorrection, 84 | int nlevels, bool signedGradient); 85 | 86 | extern "C" 87 | void HOGDescriptor_dtor(struct HOGDescriptorPtr ptr); 88 | 89 | extern "C" 90 | size_t HOGDescriptor_getDescriptorSize(struct HOGDescriptorPtr ptr); 91 | 92 | extern "C" 93 | bool HOGDescriptor_checkDetectorSize(struct HOGDescriptorPtr ptr); 94 | 95 | extern "C" 96 | double HOGDescriptor_getWinSigma(struct HOGDescriptorPtr ptr); 97 | 98 | extern "C" 99 | void HOGDescriptor_setSVMDetector(struct HOGDescriptorPtr ptr, struct TensorWrapper _svmdetector); 100 | 101 | extern "C" 102 | bool HOGDescriptor_load( 103 | struct HOGDescriptorPtr ptr, const char *filename, const char *objname); 104 | 105 | extern "C" 106 | void HOGDescriptor_save( 107 | struct HOGDescriptorPtr ptr, const char *filename, const char *objname); 108 | 109 | extern "C" 110 | struct TensorWrapper HOGDescriptor_compute( 111 | struct HOGDescriptorPtr ptr, struct TensorWrapper img, struct SizeWrapper winStride, 112 | struct SizeWrapper padding, struct PointArray locations); 113 | 114 | extern "C" 115 | struct TensorPlusPointArray HOGDescriptor_detect( 116 | struct HOGDescriptorPtr ptr, struct TensorWrapper img, double hitThreshold, 117 | struct SizeWrapper winStride, struct SizeWrapper padding, struct PointArray searchLocations); 118 | 119 | extern "C" 120 | struct TensorPlusRectArray HOGDescriptor_detectMultiScale( 121 | struct HOGDescriptorPtr ptr, struct TensorWrapper img, double hitThreshold, 122 | struct SizeWrapper winStride, struct SizeWrapper padding, double scale, 123 | double finalThreshold, bool useMeanshiftGrouping); 124 | 125 | extern "C" 126 | struct TensorArray HOGDescriptor_computeGradient( 127 | struct HOGDescriptorPtr ptr, struct TensorWrapper img, 128 | struct SizeWrapper paddingTL, struct SizeWrapper paddingBR); 129 | 130 | extern "C" 131 | struct TensorWrapper HOGDescriptor_getDefaultPeopleDetector(); 132 | 133 | extern "C" 134 | struct TensorWrapper HOGDescriptor_getDaimlerPeopleDetector(); 135 | 136 | -------------------------------------------------------------------------------- /include/cudastereo.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // StereoBM 6 | 7 | struct StereoBMPtr { 8 | void *ptr; 9 | inline cuda::StereoBM * operator->() { return static_cast(ptr); } 10 | inline StereoBMPtr(cuda::StereoBM *ptr) { this->ptr = ptr; } 11 | inline cuda::StereoBM & operator*() { return *static_cast(this->ptr); } 12 | }; 13 | 14 | // StereoBeliefPropagation 15 | 16 | struct StereoBeliefPropagationPtr { 17 | void *ptr; 18 | inline cuda::StereoBeliefPropagation * operator->() { return static_cast(ptr); } 19 | inline StereoBeliefPropagationPtr(cuda::StereoBeliefPropagation *ptr) { this->ptr = ptr; } 20 | inline cuda::StereoBeliefPropagation & operator*() { return *static_cast(this->ptr); } 21 | }; 22 | 23 | // StereoConstantSpaceBP 24 | 25 | struct StereoConstantSpaceBPPtr { 26 | void *ptr; 27 | inline cuda::StereoConstantSpaceBP * operator->() { return static_cast(ptr); } 28 | inline StereoConstantSpaceBPPtr(cuda::StereoConstantSpaceBP *ptr) { this->ptr = ptr; } 29 | inline cuda::StereoConstantSpaceBP & operator*() { return *static_cast(this->ptr); } 30 | }; 31 | 32 | // DisparityBilateralFilter 33 | 34 | struct DisparityBilateralFilterPtr { 35 | void *ptr; 36 | inline cuda::DisparityBilateralFilter * operator->() { return static_cast(ptr); } 37 | inline DisparityBilateralFilterPtr(cuda::DisparityBilateralFilter *ptr) { this->ptr = ptr; } 38 | inline cuda::DisparityBilateralFilter & operator*() { return *static_cast(this->ptr); } 39 | }; 40 | 41 | extern "C" 42 | struct StereoBMPtr createStereoBMCuda(int numDisparities, int blockSize); 43 | 44 | extern "C" 45 | struct TensorWrapper StereoBM_computeCuda(struct cutorchInfo info, struct StereoBMPtr ptr, 46 | struct TensorWrapper left, struct TensorWrapper right, struct TensorWrapper disparity); 47 | 48 | extern "C" 49 | struct StereoBeliefPropagationPtr createStereoBeliefPropagationCuda( 50 | int ndisp, int iters, int levels, int msg_type); 51 | 52 | extern "C" 53 | struct TensorWrapper StereoBeliefPropagation_computeCuda(struct cutorchInfo info, 54 | struct StereoBeliefPropagationPtr ptr, struct TensorWrapper left, 55 | struct TensorWrapper right, struct TensorWrapper disparity); 56 | 57 | extern "C" 58 | struct TensorWrapper StereoBeliefPropagation_compute2Cuda(struct cutorchInfo info, 59 | struct StereoBeliefPropagationPtr ptr, struct TensorWrapper data, 60 | struct TensorWrapper disparity); 61 | 62 | extern "C" 63 | void StereoBeliefPropagation_setNumItersCuda(struct StereoBeliefPropagationPtr ptr, int val); 64 | 65 | extern "C" 66 | int StereoBeliefPropagation_getNumItersCuda(struct StereoBeliefPropagationPtr ptr); 67 | 68 | extern "C" 69 | void StereoBeliefPropagation_setNumLevelsCuda(struct StereoBeliefPropagationPtr ptr, int val); 70 | 71 | extern "C" 72 | int StereoBeliefPropagation_getNumLevelsCuda(struct StereoBeliefPropagationPtr ptr); 73 | 74 | extern "C" 75 | void StereoBeliefPropagation_setMaxDataTermCuda(struct StereoBeliefPropagationPtr ptr, double val); 76 | 77 | extern "C" 78 | double StereoBeliefPropagation_getMaxDataTermCuda(struct StereoBeliefPropagationPtr ptr); 79 | 80 | extern "C" 81 | void StereoBeliefPropagation_setDataWeightCuda(struct StereoBeliefPropagationPtr ptr, double val); 82 | 83 | extern "C" 84 | double StereoBeliefPropagation_getDataWeightCuda(struct StereoBeliefPropagationPtr ptr); 85 | 86 | extern "C" 87 | void StereoBeliefPropagation_setMaxDiscTermCuda(struct StereoBeliefPropagationPtr ptr, double val); 88 | 89 | extern "C" 90 | double StereoBeliefPropagation_getMaxDiscTermCuda(struct StereoBeliefPropagationPtr ptr); 91 | 92 | extern "C" 93 | void StereoBeliefPropagation_setDiscSingleJumpCuda(struct StereoBeliefPropagationPtr ptr, double val); 94 | 95 | extern "C" 96 | double StereoBeliefPropagation_getDiscSingleJumpCuda(struct StereoBeliefPropagationPtr ptr); 97 | 98 | extern "C" 99 | void StereoBeliefPropagation_setMsgTypeCuda(struct StereoBeliefPropagationPtr ptr, int val); 100 | 101 | extern "C" 102 | int StereoBeliefPropagation_getMsgTypeCuda(struct StereoBeliefPropagationPtr ptr); 103 | 104 | extern "C" 105 | struct Vec3iWrapper StereoBeliefPropagation_estimateRecommendedParamsCuda(int width, int height); 106 | 107 | extern "C" 108 | int StereoConstantSpaceBP_getNrPlaneCuda(struct StereoConstantSpaceBPPtr ptr); 109 | 110 | extern "C" 111 | void StereoConstantSpaceBP_setNrPlaneCuda(struct StereoConstantSpaceBPPtr ptr, int val); 112 | 113 | extern "C" 114 | bool StereoConstantSpaceBP_getUseLocalInitDataCostCuda(struct StereoConstantSpaceBPPtr ptr); 115 | 116 | extern "C" 117 | void StereoConstantSpaceBP_setUseLocalInitDataCostCuda(struct StereoConstantSpaceBPPtr ptr, bool val); 118 | 119 | extern "C" 120 | struct Vec4iWrapper StereoConstantSpaceBP_estimateRecommendedParamsCuda(int width, int height); 121 | 122 | extern "C" 123 | struct StereoConstantSpaceBPPtr createStereoConstantSpaceBPCuda( 124 | int ndisp, int iters, int levels, int nr_plane, int msg_type); 125 | 126 | extern "C" 127 | struct TensorWrapper reprojectImageTo3DCuda( 128 | struct cutorchInfo info, struct TensorWrapper disp, 129 | struct TensorWrapper xyzw, struct TensorWrapper Q, int dst_cn); 130 | 131 | extern "C" 132 | struct TensorWrapper drawColorDispCuda( 133 | struct cutorchInfo info, struct TensorWrapper src_disp, 134 | struct TensorWrapper dst_disp, int ndisp); 135 | -------------------------------------------------------------------------------- /src/ximgproc.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | extern "C" 4 | struct TensorWrapper niBlackThreshold(struct TensorWrapper src, struct TensorWrapper dst, double maxValue, int type, int blockSize, double delta) { 5 | 6 | MatT dst_mat = dst.toMatT(); 7 | cv::ximgproc::niBlackThreshold(src.toMat(), dst_mat, maxValue, type, blockSize, delta); 8 | return TensorWrapper(dst_mat); 9 | } 10 | 11 | // GraphSegmentation 12 | 13 | extern "C" 14 | struct GraphSegmentationPtr GraphSegmentation_ctor(double sigma, float k, int min_size) { 15 | return rescueObjectFromPtr(cv::ximgproc::segmentation::createGraphSegmentation(sigma, k, min_size)); 16 | } 17 | 18 | extern "C" 19 | void GraphSegmentation_dtor(struct GraphSegmentationPtr ptr) { 20 | delete static_cast(ptr.ptr); 21 | } 22 | 23 | extern "C" 24 | struct TensorWrapper GraphSegmentation_processImage(struct GraphSegmentationPtr ptr, struct TensorWrapper img) { 25 | 26 | cv::Mat result; 27 | ptr->processImage(img.toMat(), result); 28 | return TensorWrapper(result); 29 | } 30 | 31 | extern "C" 32 | void GraphSegmentation_setSigma(struct GraphSegmentationPtr ptr, double s) { 33 | ptr->setSigma(s); 34 | } 35 | 36 | extern "C" 37 | double GraphSegmentation_getSigma(struct GraphSegmentationPtr ptr) { 38 | return ptr->getSigma(); 39 | } 40 | 41 | extern "C" 42 | void GraphSegmentation_setK(struct GraphSegmentationPtr ptr, float k) { 43 | ptr->setK(k); 44 | } 45 | 46 | extern "C" 47 | float GraphSegmentation_getK(struct GraphSegmentationPtr ptr) { 48 | return ptr->getK(); 49 | } 50 | 51 | extern "C" 52 | void GraphSegmentation_setMinSize(struct GraphSegmentationPtr ptr, int min_size) { 53 | ptr->setMinSize(min_size); 54 | } 55 | 56 | extern "C" 57 | int GraphSegmentation_getMinSize(struct GraphSegmentationPtr ptr) { 58 | return ptr->getMinSize(); 59 | } 60 | 61 | // SLIC 62 | 63 | extern "C" 64 | struct SuperpixelSLICPtr SuperpixelSLIC_ctor( 65 | struct TensorWrapper image, int algorithm, 66 | int region_size, float ruler) { 67 | return rescueObjectFromPtr(cv::ximgproc::createSuperpixelSLIC( 68 | image.toMat(), algorithm, region_size, ruler)); 69 | } 70 | 71 | extern "C" 72 | int SuperpixelSLIC_getNumberOfSuperpixels(struct SuperpixelSLICPtr ptr) { 73 | return ptr->getNumberOfSuperpixels(); 74 | } 75 | 76 | extern "C" 77 | void SuperpixelSLIC_iterate(struct SuperpixelSLICPtr ptr, int num_iterations) { 78 | ptr->iterate(num_iterations); 79 | } 80 | 81 | extern "C" 82 | struct TensorWrapper SuperpixelSLIC_getLabels( 83 | struct SuperpixelSLICPtr ptr, struct TensorWrapper labels_out) { 84 | MatT labels_outMat = labels_out.toMatT(); 85 | ptr->getLabels(labels_outMat); 86 | return labels_outMat; 87 | } 88 | 89 | extern "C" 90 | struct TensorWrapper SuperpixelSLIC_getLabelContourMask( 91 | struct SuperpixelSLICPtr ptr, struct TensorWrapper image, bool thick_line) { 92 | MatT imageMat = image.toMatT(); 93 | ptr->getLabelContourMask(imageMat, thick_line); 94 | return imageMat; 95 | } 96 | 97 | extern "C" 98 | void SuperpixelSLIC_enforceLabelConnectivity( 99 | struct SuperpixelSLICPtr ptr, int min_element_size) { 100 | ptr->enforceLabelConnectivity(min_element_size); 101 | } 102 | 103 | // See #103 and #95 104 | /* 105 | 106 | // SelectiveSearchSegmentation 107 | 108 | extern "C" 109 | struct SelectiveSearchSegmentationPtr SelectiveSearchSegmentation_ctor() { 110 | return rescueObjectFromPtr(cv::ximgproc::segmentation::createSelectiveSearchSegmentation()); 111 | } 112 | 113 | extern "C" 114 | void SelectiveSearchSegmentationPtr_dtor(struct SelectiveSearchSegmentationPtr ptr) { 115 | delete static_cast(ptr.ptr); 116 | } 117 | 118 | extern "C" 119 | void SelectiveSearchSegmentation_setBaseImage(struct SelectiveSearchSegmentationPtr ptr, struct TensorWrapper img) { 120 | ptr->setBaseImage(img.toMat()); 121 | } 122 | 123 | extern "C" 124 | void SelectiveSearchSegmentation_switchToSingleStrategy(struct SelectiveSearchSegmentationPtr ptr, int k, float sigma) { 125 | ptr->switchToSingleStrategy(k, sigma); 126 | } 127 | 128 | extern "C" 129 | void SelectiveSearchSegmentation_switchToSelectiveSearchFast(struct SelectiveSearchSegmentationPtr ptr, int k, int inc_k, float sigma) { 130 | ptr->switchToSelectiveSearchFast(k, inc_k, sigma); 131 | } 132 | 133 | extern "C" 134 | void SelectiveSearchSegmentation_switchToSelectiveSearchQuality(struct SelectiveSearchSegmentationPtr ptr, int k, int inc_k, float sigma) { 135 | ptr->switchToSelectiveSearchQuality(k, inc_k, sigma); 136 | } 137 | 138 | extern "C" 139 | void SelectiveSearchSegmentation_addImage(struct SelectiveSearchSegmentationPtr ptr, struct TensorWrapper img) { 140 | ptr->setBaseImage(img.toMat()); 141 | } 142 | 143 | extern "C" 144 | void SelectiveSearchSegmentation_clearImages(struct SelectiveSearchSegmentationPtr ptr) { 145 | ptr->clearImages(); 146 | } 147 | 148 | extern "C" 149 | void SelectiveSearchSegmentation_addGraphSegmentation(struct SelectiveSearchSegmentationPtr ptr, struct GraphSegmentationPtr gs) { 150 | ptr->addGraphSegmentation(*gs); 151 | } 152 | 153 | extern "C" 154 | void SelectiveSearchSegmentation_clearGraphSegmentations(struct SelectiveSearchSegmentationPtr ptr) { 155 | ptr->clearGraphSegmentations(); 156 | } 157 | 158 | extern "C" 159 | void SelectiveSearchSegmentation_addStrategy(struct SelectiveSearchSegmentationPtr ptr, struct SelectiveSearchSegmentationStrategyPtr s) { 160 | ptr->addStrategy(*s); 161 | } 162 | 163 | extern "C" 164 | void SelectiveSearchSegmentation_clearStrategies(struct SelectiveSearchSegmentationPtr ptr) { 165 | ptr->clearStrategies(); 166 | } 167 | 168 | extern "C" 169 | struct RectArray SelectiveSearchSegmentation_process(struct SelectiveSearchSegmentationPtr ptr) { 170 | 171 | std::vector result; 172 | ptr->process(result); 173 | 174 | return RectArray(result); 175 | } 176 | */ -------------------------------------------------------------------------------- /include/flann.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace flann = cv::flann; 5 | 6 | struct IndexPtr { 7 | void *ptr; 8 | 9 | inline flann::Index * operator->() { return static_cast(ptr); } 10 | inline IndexPtr(flann::Index *ptr) { this->ptr = ptr; } 11 | }; 12 | 13 | // Various IndexParams 14 | 15 | struct IndexParamsPtr { 16 | void *ptr; 17 | 18 | inline flann::IndexParams * operator->() { return static_cast(ptr); } 19 | inline IndexParamsPtr(flann::IndexParams *ptr) { this->ptr = ptr; } 20 | inline operator const flann::IndexParams &() { return *static_cast(ptr); } 21 | }; 22 | 23 | struct KDTreeIndexParamsPtr { 24 | void *ptr; 25 | 26 | inline flann::KDTreeIndexParams * operator->() { return static_cast(ptr); } 27 | inline KDTreeIndexParamsPtr(flann::KDTreeIndexParams *ptr) { this->ptr = ptr; } 28 | }; 29 | 30 | struct LinearIndexParamsPtr { 31 | void *ptr; 32 | 33 | inline flann::LinearIndexParams * operator->() { return static_cast(ptr); } 34 | inline LinearIndexParamsPtr(flann::LinearIndexParams *ptr) { this->ptr = ptr; } 35 | }; 36 | 37 | struct CompositeIndexParamsPtr { 38 | void *ptr; 39 | 40 | inline flann::CompositeIndexParams * operator->() { return static_cast(ptr); } 41 | inline CompositeIndexParamsPtr(flann::CompositeIndexParams *ptr) { this->ptr = ptr; } 42 | }; 43 | 44 | struct AutotunedIndexParamsPtr { 45 | void *ptr; 46 | 47 | inline flann::AutotunedIndexParams * operator->() { return static_cast(ptr); } 48 | inline AutotunedIndexParamsPtr(flann::AutotunedIndexParams *ptr) { this->ptr = ptr; } 49 | }; 50 | 51 | struct HierarchicalClusteringIndexParamsPtr { 52 | void *ptr; 53 | 54 | inline flann::HierarchicalClusteringIndexParams * operator->() { return static_cast(ptr); } 55 | inline HierarchicalClusteringIndexParamsPtr(flann::HierarchicalClusteringIndexParams *ptr) { this->ptr = ptr; } 56 | }; 57 | 58 | struct KMeansIndexParamsPtr { 59 | void *ptr; 60 | 61 | inline flann::KMeansIndexParams * operator->() { return static_cast(ptr); } 62 | inline KMeansIndexParamsPtr(flann::KMeansIndexParams *ptr) { this->ptr = ptr; } 63 | }; 64 | 65 | struct LshIndexParamsPtr { 66 | void *ptr; 67 | 68 | inline flann::LshIndexParams * operator->() { return static_cast(ptr); } 69 | inline LshIndexParamsPtr(flann::LshIndexParams *ptr) { this->ptr = ptr; } 70 | }; 71 | 72 | struct SavedIndexParamsPtr { 73 | void *ptr; 74 | 75 | inline flann::SavedIndexParams * operator->() { return static_cast(ptr); } 76 | inline SavedIndexParamsPtr(flann::SavedIndexParams *ptr) { this->ptr = ptr; } 77 | }; 78 | 79 | struct SearchParamsPtr { 80 | void *ptr; 81 | 82 | inline flann::SearchParams * operator->() { return static_cast(ptr); } 83 | inline SearchParamsPtr(flann::SearchParams *ptr) { this->ptr = ptr; } 84 | inline operator const flann::SearchParams &() { return *static_cast(ptr); } 85 | }; 86 | 87 | extern "C" 88 | void IndexParams_dtor(struct IndexParamsPtr ptr); 89 | 90 | extern "C" 91 | struct KDTreeIndexParamsPtr KDTreeIndexParams_ctor(int trees); 92 | 93 | extern "C" 94 | struct LinearIndexParamsPtr LinearIndexParams_ctor(); 95 | 96 | extern "C" 97 | struct CompositeIndexParamsPtr CompositeIndexParams_ctor( 98 | int trees, int branching, int iterations, 99 | cvflann::flann_centers_init_t centers_init, float cb_index); 100 | 101 | extern "C" 102 | struct AutotunedIndexParamsPtr AutotunedIndexParams_ctor( 103 | float target_precision, float build_weight, 104 | float memory_weight, float sample_fraction); 105 | 106 | extern "C" 107 | struct HierarchicalClusteringIndexParamsPtr HierarchicalClusteringIndexParams_ctor( 108 | int branching, cvflann::flann_centers_init_t centers_init, int trees, int leaf_size); 109 | 110 | extern "C" 111 | struct KMeansIndexParamsPtr KMeansIndexParams_ctor( 112 | int branching, int iterations, cvflann::flann_centers_init_t centers_init, float cb_index); 113 | 114 | extern "C" 115 | struct LshIndexParamsPtr LshIndexParams_ctor( 116 | int table_number, int key_size, int multi_probe_level); 117 | 118 | extern "C" 119 | struct SavedIndexParamsPtr SavedIndexParams_ctor(const char *filename); 120 | 121 | extern "C" 122 | struct SearchParamsPtr SearchParams_ctor(int checks, float eps, bool sorted); 123 | 124 | extern "C" 125 | struct IndexPtr Index_ctor_default(); 126 | 127 | extern "C" 128 | struct IndexPtr Index_ctor( 129 | struct TensorWrapper features, struct IndexParamsPtr params, 130 | cvflann::flann_distance_t distType); 131 | 132 | extern "C" 133 | void Index_dtor(struct IndexPtr ptr); 134 | 135 | extern "C" 136 | void Index_build( 137 | struct IndexPtr ptr, struct TensorWrapper features, 138 | struct IndexParamsPtr params, cvflann::flann_distance_t distType); 139 | 140 | extern "C" 141 | struct TensorArray Index_knnSearch( 142 | struct IndexPtr ptr, struct TensorWrapper query, int knn, struct TensorWrapper indices, 143 | struct TensorWrapper dists, struct SearchParamsPtr params); 144 | 145 | extern "C" 146 | struct TensorArrayPlusInt Index_radiusSearch( 147 | struct IndexPtr ptr, struct TensorWrapper query, double radius, int maxResults, 148 | struct TensorWrapper indices, struct TensorWrapper dists, struct SearchParamsPtr params); 149 | 150 | extern "C" 151 | void Index_save(struct IndexPtr ptr, const char *filename); 152 | 153 | extern "C" 154 | bool Index_load(struct IndexPtr ptr, struct TensorWrapper features, const char *filename); 155 | 156 | extern "C" 157 | void Index_release(struct IndexPtr ptr); 158 | 159 | extern "C" 160 | int Index_getDistance(struct IndexPtr ptr); 161 | 162 | extern "C" 163 | int Index_getAlgorithm(struct IndexPtr ptr); 164 | -------------------------------------------------------------------------------- /include/cudabgsegm.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // BackgroundSubtractorMOG 6 | 7 | struct BackgroundSubtractorMOGPtr { 8 | void *ptr; 9 | inline cuda::BackgroundSubtractorMOG * operator->() { return static_cast(ptr); } 10 | inline BackgroundSubtractorMOGPtr(cuda::BackgroundSubtractorMOG *ptr) { this->ptr = ptr; } 11 | inline cuda::BackgroundSubtractorMOG & operator*() { return *static_cast(this->ptr); } 12 | }; 13 | 14 | // BackgroundSubtractorMOG2 15 | 16 | struct BackgroundSubtractorMOG2Ptr { 17 | void *ptr; 18 | inline cuda::BackgroundSubtractorMOG2 * operator->() { return static_cast(ptr); } 19 | inline BackgroundSubtractorMOG2Ptr(cuda::BackgroundSubtractorMOG2 *ptr) { this->ptr = ptr; } 20 | inline cuda::BackgroundSubtractorMOG2 & operator*() { return *static_cast(this->ptr); } 21 | }; 22 | 23 | extern "C" 24 | struct BackgroundSubtractorMOGPtr BackgroundSubtractorMOG_ctorCuda( 25 | int History, int NMixtures, double BackgroundRatio, double NoiseSigma); 26 | 27 | extern "C" 28 | struct TensorWrapper BackgroundSubtractorMOG_applyCuda(struct cutorchInfo info, 29 | struct BackgroundSubtractorMOGPtr ptr, struct TensorWrapper image, 30 | struct TensorWrapper fgmask, double learningRate); 31 | 32 | extern "C" 33 | struct TensorWrapper BackgroundSubtractorMOG_getBackgroundImageCuda( 34 | struct cutorchInfo info, struct BackgroundSubtractorMOGPtr ptr, 35 | struct TensorWrapper backgroundImage); 36 | 37 | extern "C" 38 | void BackgroundSubtractorMOG_setHistoryCuda(struct BackgroundSubtractorMOGPtr ptr, int val); 39 | 40 | extern "C" 41 | int BackgroundSubtractorMOG_getHistoryCuda(struct BackgroundSubtractorMOGPtr ptr); 42 | 43 | extern "C" 44 | void BackgroundSubtractorMOG_setNMixturesCuda(struct BackgroundSubtractorMOGPtr ptr, int val); 45 | 46 | extern "C" 47 | int BackgroundSubtractorMOG_getNMixturesCuda(struct BackgroundSubtractorMOGPtr ptr); 48 | 49 | extern "C" 50 | void BackgroundSubtractorMOG_setBackgroundRatioCuda(struct BackgroundSubtractorMOGPtr ptr, double val); 51 | 52 | extern "C" 53 | double BackgroundSubtractorMOG_getBackgroundRatioCuda(struct BackgroundSubtractorMOGPtr ptr); 54 | 55 | extern "C" 56 | void BackgroundSubtractorMOG_setNoiseSigmaCuda(struct BackgroundSubtractorMOGPtr ptr, double val); 57 | 58 | extern "C" 59 | double BackgroundSubtractorMOG_getNoiseSigmaCuda(struct BackgroundSubtractorMOGPtr ptr); 60 | 61 | extern "C" 62 | struct BackgroundSubtractorMOG2Ptr BackgroundSubtractorMOG2_ctorCuda( 63 | int history, double varThreshold, bool detectShadows); 64 | 65 | extern "C" 66 | struct TensorWrapper BackgroundSubtractorMOG2_applyCuda(struct cutorchInfo info, 67 | struct BackgroundSubtractorMOG2Ptr ptr, struct TensorWrapper image, 68 | struct TensorWrapper fgmask, double learningRate); 69 | 70 | extern "C" 71 | struct TensorWrapper BackgroundSubtractorMOG2_getBackgroundImageCuda( 72 | struct cutorchInfo info, struct BackgroundSubtractorMOG2Ptr ptr, 73 | struct TensorWrapper backgroundImage); 74 | 75 | extern "C" 76 | int BackgroundSubtractorMOG2_getHistoryCuda(struct BackgroundSubtractorMOG2Ptr ptr); 77 | 78 | extern "C" 79 | void BackgroundSubtractorMOG2_setHistoryCuda(struct BackgroundSubtractorMOG2Ptr ptr, int history); 80 | 81 | extern "C" 82 | int BackgroundSubtractorMOG2_getNMixturesCuda(struct BackgroundSubtractorMOG2Ptr ptr); 83 | 84 | extern "C" 85 | void BackgroundSubtractorMOG2_setNMixturesCuda(struct BackgroundSubtractorMOG2Ptr ptr, int nmixtures); 86 | 87 | extern "C" 88 | int BackgroundSubtractorMOG2_getShadowValueCuda(struct BackgroundSubtractorMOG2Ptr ptr); 89 | 90 | extern "C" 91 | void BackgroundSubtractorMOG2_setShadowValueCuda(struct BackgroundSubtractorMOG2Ptr ptr, int shadow_value); 92 | 93 | extern "C" 94 | double BackgroundSubtractorMOG2_getBackgroundRatioCuda(struct BackgroundSubtractorMOG2Ptr ptr); 95 | 96 | extern "C" 97 | void BackgroundSubtractorMOG2_setBackgroundRatioCuda(struct BackgroundSubtractorMOG2Ptr ptr, double ratio); 98 | 99 | extern "C" 100 | double BackgroundSubtractorMOG2_getVarThresholdCuda(struct BackgroundSubtractorMOG2Ptr ptr); 101 | 102 | extern "C" 103 | void BackgroundSubtractorMOG2_setVarThresholdCuda(struct BackgroundSubtractorMOG2Ptr ptr, double varThreshold); 104 | 105 | extern "C" 106 | double BackgroundSubtractorMOG2_getVarThresholdGenCuda(struct BackgroundSubtractorMOG2Ptr ptr); 107 | 108 | extern "C" 109 | void BackgroundSubtractorMOG2_setVarThresholdGenCuda(struct BackgroundSubtractorMOG2Ptr ptr, double varThresholdGen); 110 | 111 | extern "C" 112 | double BackgroundSubtractorMOG2_getVarInitCuda(struct BackgroundSubtractorMOG2Ptr ptr); 113 | 114 | extern "C" 115 | void BackgroundSubtractorMOG2_setVarInitCuda(struct BackgroundSubtractorMOG2Ptr ptr, double varInit); 116 | 117 | extern "C" 118 | double BackgroundSubtractorMOG2_getVarMinCuda(struct BackgroundSubtractorMOG2Ptr ptr); 119 | 120 | extern "C" 121 | void BackgroundSubtractorMOG2_setVarMinCuda(struct BackgroundSubtractorMOG2Ptr ptr, double varMin); 122 | 123 | extern "C" 124 | double BackgroundSubtractorMOG2_getVarMaxCuda(struct BackgroundSubtractorMOG2Ptr ptr); 125 | 126 | extern "C" 127 | void BackgroundSubtractorMOG2_setVarMaxCuda(struct BackgroundSubtractorMOG2Ptr ptr, double varMax); 128 | 129 | extern "C" 130 | bool BackgroundSubtractorMOG2_getDetectShadowsCuda(struct BackgroundSubtractorMOG2Ptr ptr); 131 | 132 | extern "C" 133 | void BackgroundSubtractorMOG2_setDetectShadowsCuda(struct BackgroundSubtractorMOG2Ptr ptr, bool detectShadows); 134 | 135 | extern "C" 136 | double BackgroundSubtractorMOG2_getComplexityReductionThresholdCuda(struct BackgroundSubtractorMOG2Ptr ptr); 137 | 138 | extern "C" 139 | void BackgroundSubtractorMOG2_setComplexityReductionThresholdCuda(struct BackgroundSubtractorMOG2Ptr ptr, double ct); 140 | 141 | extern "C" 142 | double BackgroundSubtractorMOG2_getShadowThresholdCuda(struct BackgroundSubtractorMOG2Ptr ptr); 143 | 144 | extern "C" 145 | void BackgroundSubtractorMOG2_setShadowThresholdCuda(struct BackgroundSubtractorMOG2Ptr ptr, double shadowThreshold); 146 | -------------------------------------------------------------------------------- /src/cudastereo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | extern "C" 4 | struct StereoBMPtr createStereoBMCuda(int numDisparities, int blockSize) 5 | { 6 | return rescueObjectFromPtr(cuda::createStereoBM(numDisparities, blockSize)); 7 | } 8 | 9 | extern "C" 10 | struct TensorWrapper StereoBM_computeCuda(struct cutorchInfo info, struct StereoBMPtr ptr, 11 | struct TensorWrapper left, struct TensorWrapper right, struct TensorWrapper disparity) 12 | { 13 | cuda::GpuMat retval = disparity.toGpuMat(); 14 | ptr->compute(left.toGpuMat(), right.toGpuMat(), retval, prepareStream(info)); 15 | return TensorWrapper(retval, info.state); 16 | } 17 | 18 | extern "C" 19 | struct StereoBeliefPropagationPtr createStereoBeliefPropagationCuda( 20 | int ndisp, int iters, int levels, int msg_type) 21 | { 22 | return rescueObjectFromPtr(cuda::createStereoBeliefPropagation( 23 | ndisp, iters, levels, msg_type)); 24 | } 25 | 26 | extern "C" 27 | struct TensorWrapper StereoBeliefPropagation_computeCuda(struct cutorchInfo info, 28 | struct StereoBeliefPropagationPtr ptr, struct TensorWrapper left, 29 | struct TensorWrapper right, struct TensorWrapper disparity) 30 | { 31 | cuda::GpuMat retval = disparity.toGpuMat(); 32 | ptr->compute(left.toGpuMat(), right.toGpuMat(), retval, prepareStream(info)); 33 | return TensorWrapper(retval, info.state); 34 | } 35 | 36 | extern "C" 37 | struct TensorWrapper StereoBeliefPropagation_compute2Cuda(struct cutorchInfo info, 38 | struct StereoBeliefPropagationPtr ptr, struct TensorWrapper data, 39 | struct TensorWrapper disparity) 40 | { 41 | cuda::GpuMat retval = disparity.toGpuMat(); 42 | ptr->compute(data.toGpuMat(), retval, prepareStream(info)); 43 | return TensorWrapper(retval, info.state); 44 | } 45 | 46 | extern "C" 47 | void StereoBeliefPropagation_setNumItersCuda(struct StereoBeliefPropagationPtr ptr, int val) 48 | { 49 | ptr->setNumIters(val); 50 | } 51 | 52 | extern "C" 53 | int StereoBeliefPropagation_getNumItersCuda(struct StereoBeliefPropagationPtr ptr) 54 | { 55 | return ptr->getNumIters(); 56 | } 57 | 58 | extern "C" 59 | void StereoBeliefPropagation_setNumLevelsCuda(struct StereoBeliefPropagationPtr ptr, int val) 60 | { 61 | ptr->setNumLevels(val); 62 | } 63 | 64 | extern "C" 65 | int StereoBeliefPropagation_getNumLevelsCuda(struct StereoBeliefPropagationPtr ptr) 66 | { 67 | return ptr->getNumLevels(); 68 | } 69 | 70 | extern "C" 71 | void StereoBeliefPropagation_setMaxDataTermCuda(struct StereoBeliefPropagationPtr ptr, double val) 72 | { 73 | ptr->setMaxDataTerm(val); 74 | } 75 | 76 | extern "C" 77 | double StereoBeliefPropagation_getMaxDataTermCuda(struct StereoBeliefPropagationPtr ptr) 78 | { 79 | return ptr->getMaxDataTerm(); 80 | } 81 | 82 | extern "C" 83 | void StereoBeliefPropagation_setDataWeightCuda(struct StereoBeliefPropagationPtr ptr, double val) 84 | { 85 | ptr->setDataWeight(val); 86 | } 87 | 88 | extern "C" 89 | double StereoBeliefPropagation_getDataWeightCuda(struct StereoBeliefPropagationPtr ptr) 90 | { 91 | return ptr->getDataWeight(); 92 | } 93 | 94 | extern "C" 95 | void StereoBeliefPropagation_setMaxDiscTermCuda(struct StereoBeliefPropagationPtr ptr, double val) 96 | { 97 | ptr->setMaxDiscTerm(val); 98 | } 99 | 100 | extern "C" 101 | double StereoBeliefPropagation_getMaxDiscTermCuda(struct StereoBeliefPropagationPtr ptr) 102 | { 103 | return ptr->getMaxDiscTerm(); 104 | } 105 | 106 | extern "C" 107 | void StereoBeliefPropagation_setDiscSingleJumpCuda(struct StereoBeliefPropagationPtr ptr, double val) 108 | { 109 | ptr->setDiscSingleJump(val); 110 | } 111 | 112 | extern "C" 113 | double StereoBeliefPropagation_getDiscSingleJumpCuda(struct StereoBeliefPropagationPtr ptr) 114 | { 115 | return ptr->getDiscSingleJump(); 116 | } 117 | 118 | extern "C" 119 | void StereoBeliefPropagation_setMsgTypeCuda(struct StereoBeliefPropagationPtr ptr, int val) 120 | { 121 | ptr->setMsgType(val); 122 | } 123 | 124 | extern "C" 125 | int StereoBeliefPropagation_getMsgTypeCuda(struct StereoBeliefPropagationPtr ptr) 126 | { 127 | return ptr->getMsgType(); 128 | } 129 | 130 | extern "C" 131 | struct Vec3iWrapper StereoBeliefPropagation_estimateRecommendedParamsCuda(int width, int height) 132 | { 133 | struct Vec3iWrapper retval; 134 | cuda::StereoBeliefPropagation::estimateRecommendedParams( 135 | width, height, retval.v0, retval.v1, retval.v2); 136 | return retval; 137 | } 138 | 139 | extern "C" 140 | int StereoConstantSpaceBP_getNrPlaneCuda(struct StereoConstantSpaceBPPtr ptr) 141 | { 142 | return ptr->getNrPlane(); 143 | } 144 | 145 | extern "C" 146 | void StereoConstantSpaceBP_setNrPlaneCuda(struct StereoConstantSpaceBPPtr ptr, int val) 147 | { 148 | ptr->setNrPlane(val); 149 | } 150 | 151 | extern "C" 152 | bool StereoConstantSpaceBP_getUseLocalInitDataCostCuda(struct StereoConstantSpaceBPPtr ptr) 153 | { 154 | return ptr->getUseLocalInitDataCost(); 155 | } 156 | 157 | extern "C" 158 | void StereoConstantSpaceBP_setUseLocalInitDataCostCuda(struct StereoConstantSpaceBPPtr ptr, bool val) 159 | { 160 | ptr->setUseLocalInitDataCost(val); 161 | } 162 | 163 | extern "C" 164 | struct Vec4iWrapper StereoConstantSpaceBP_estimateRecommendedParamsCuda(int width, int height) 165 | { 166 | Vec4iWrapper retval; 167 | cuda::StereoConstantSpaceBP::estimateRecommendedParams( 168 | width, height, retval.v0, retval.v1, retval.v2, retval.v3); 169 | return retval; 170 | } 171 | 172 | extern "C" 173 | struct StereoConstantSpaceBPPtr createStereoConstantSpaceBPCuda( 174 | int ndisp, int iters, int levels, int nr_plane, int msg_type) 175 | { 176 | return rescueObjectFromPtr(cuda::createStereoConstantSpaceBP( 177 | ndisp, iters, levels, nr_plane, msg_type)); 178 | } 179 | 180 | extern "C" 181 | struct TensorWrapper reprojectImageTo3DCuda( 182 | struct cutorchInfo info, struct TensorWrapper disp, 183 | struct TensorWrapper xyzw, struct TensorWrapper Q, int dst_cn) 184 | { 185 | cuda::GpuMat retval = xyzw.toGpuMat(); 186 | cuda::reprojectImageTo3D(disp.toGpuMat(), retval, Q.toGpuMat(), dst_cn, prepareStream(info)); 187 | return TensorWrapper(retval, info.state); 188 | } 189 | 190 | extern "C" 191 | struct TensorWrapper drawColorDispCuda( 192 | struct cutorchInfo info, struct TensorWrapper src_disp, 193 | struct TensorWrapper dst_disp, int ndisp) 194 | { 195 | cuda::GpuMat retval = dst_disp.toGpuMat(); 196 | cuda::drawColorDisp(src_disp.toGpuMat(), retval, ndisp, prepareStream(info)); 197 | return TensorWrapper(retval, info.state); 198 | } 199 | -------------------------------------------------------------------------------- /cv/cudacodec/init.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv._env' 2 | require 'cutorch' 3 | 4 | -- TODO: remove this after gathering all CUDA packages in a single submodule 5 | cv.cuda = cv.cuda or require 'cv._env_cuda' 6 | 7 | local ffi = require 'ffi' 8 | 9 | ffi.cdef[[ 10 | struct EncoderParams { 11 | int P_Interval; //!< NVVE_P_INTERVAL, 12 | int IDR_Period; //!< NVVE_IDR_PERIOD, 13 | int DynamicGOP; //!< NVVE_DYNAMIC_GOP, 14 | int RCType; //!< NVVE_RC_TYPE, 15 | int AvgBitrate; //!< NVVE_AVG_BITRATE, 16 | int PeakBitrate; //!< NVVE_PEAK_BITRATE, 17 | int QP_Level_Intra; //!< NVVE_QP_LEVEL_INTRA, 18 | int QP_Level_InterP; //!< NVVE_QP_LEVEL_INTER_P, 19 | int QP_Level_InterB; //!< NVVE_QP_LEVEL_INTER_B, 20 | int DeblockMode; //!< NVVE_DEBLOCK_MODE, 21 | int ProfileLevel; //!< NVVE_PROFILE_LEVEL, 22 | int ForceIntra; //!< NVVE_FORCE_INTRA, 23 | int ForceIDR; //!< NVVE_FORCE_IDR, 24 | int ClearStat; //!< NVVE_CLEAR_STAT, 25 | int DIMode; //!< NVVE_SET_DEINTERLACE, 26 | int Presets; //!< NVVE_PRESETS, 27 | int DisableCabac; //!< NVVE_DISABLE_CABAC, 28 | int NaluFramingType; //!< NVVE_CONFIGURE_NALU_FRAMING_TYPE 29 | int DisableSPSPPS; //!< NVVE_DISABLE_SPS_PPS 30 | }; 31 | 32 | struct FormatInfo { 33 | int codec; 34 | int chromaFormat; 35 | int width; 36 | int height; 37 | }; 38 | 39 | struct EncoderParams EncoderParams_ctor_defaultCuda(); 40 | 41 | struct EncoderParams EncoderParams_ctorCuda(const char *configFile); 42 | 43 | void EncoderParams_saveCuda(struct EncoderParams params, const char *configFile); 44 | 45 | struct PtrWrapper VideoWriter_ctorCuda(); 46 | 47 | void VideoWriter_dtorCuda(struct PtrWrapper ptr); 48 | 49 | void VideoWriter_writeCuda(struct PtrWrapper ptr, struct TensorWrapper frame, bool lastFrame); 50 | 51 | struct EncoderParams VideoWriter_getEncoderParamsCuda(struct PtrWrapper ptr); 52 | 53 | struct PtrWrapper VideoReader_ctorCuda(const char *filename); 54 | 55 | void VideoReader_dtorCuda(struct PtrWrapper ptr); 56 | 57 | struct TensorWrapper VideoReader_nextFrameCuda( 58 | struct cutorchInfo info, struct PtrWrapper ptr, struct TensorWrapper frame); 59 | 60 | struct FormatInfo VideoReader_formatCuda(struct PtrWrapper ptr); 61 | ]] 62 | 63 | local C = ffi.load(cv.libPath('cudacodec')) 64 | 65 | require 'cv.Classes' 66 | local Classes = ffi.load(cv.libPath('Classes')) 67 | 68 | -- TODO test this on Windows 69 | do 70 | local EncoderParams = torch.class('cuda.EncoderParams', cv.cuda) 71 | 72 | local paramNames = { 73 | P_Interval = true, 74 | IDR_Period = true, 75 | DynamicGOP = true, 76 | RCType = true, 77 | AvgBitrate = true, 78 | PeakBitrate = true, 79 | QP_Level_Intra = true, 80 | QP_Level_InterP = true, 81 | QP_Level_InterB = true, 82 | DeblockMode = true, 83 | ProfileLevel = true, 84 | ForceIntra = true, 85 | ForceIDR = true, 86 | ClearStat = true, 87 | DIMode = true, 88 | Presets = true, 89 | DisableCabac = true, 90 | NaluFramingType = true, 91 | DisableSPSPPS = true 92 | } 93 | 94 | function EncoderParams:__init(t) 95 | local argRules = { 96 | {"configFile", default = nil} 97 | } 98 | local configFile = cv.argcheck(t, argRules) 99 | 100 | if configFile then 101 | self.object = C.EncoderParams_ctorCuda(configFile) 102 | else 103 | self.object = C.EncoderParams_ctor_defaultCuda() 104 | end 105 | end 106 | 107 | function EncoderParams:__index__(key) 108 | if paramNames[key] ~= nil then 109 | return rawget(self, object)[key] 110 | else 111 | return rawget(self, key) 112 | end 113 | end 114 | 115 | function EncoderParams:load(t) 116 | local argRules = { 117 | {"configFile", required = true} 118 | } 119 | local configFile = cv.argcheck(t, argRules) 120 | 121 | self.object = C.EncoderParams_ctorCuda(configFile) 122 | end 123 | 124 | function EncoderParams:save(t) 125 | local argRules = { 126 | {"configFile", required = true} 127 | } 128 | local configFile = cv.argcheck(t, argRules) 129 | 130 | C.EncoderParams_saveCuda(self.object, configFile) 131 | end 132 | end 133 | 134 | do 135 | local VideoWriter = torch.class('cuda.VideoWriter', cv.cuda) 136 | 137 | function VideoWriter:__init(t) 138 | local argRules = { 139 | {"fileName", required = true}, 140 | {"frameSize", required = true, operator = cv.Size}, 141 | {"fps", required = true}, 142 | {"params", default = cv.cuda.EncoderParams{}}, 143 | {"format", default = cv.cuda.SF_BGR} 144 | } 145 | local fileName, frameSize, fps, params, format = cv.argcheck(t, argRules) 146 | 147 | assert(torch.type(params) == 'cuda.EncoderParams') 148 | 149 | self.ptr = ffi.gc(C.VideoWriter_ctorCuda( 150 | fileName, frameSize, fps, params, format), C.VideoWriter_dtorCuda) 151 | end 152 | 153 | function VideoWriter:write(t) 154 | local argRules = { 155 | {"frame", required = true}, 156 | {"lastFrame", default = false} 157 | } 158 | local frame, lastFrame = cv.argcheck(t, argRules) 159 | 160 | C.VideoWriter_writeCuda(self.ptr, cv.wrap_tensor(frame), lastFrame) 161 | end 162 | 163 | function VideoWriter:getEncoderParams() 164 | local retval = cv.cuda.EncoderParams{} 165 | retval.object = C.VideoWriter_getEncoderParamsCuda(self.ptr) 166 | return retval 167 | end 168 | end 169 | 170 | do 171 | local VideoReader = torch.class('cuda.VideoReader', cv.cuda) 172 | 173 | function VideoReader:__init(t) 174 | local argRules = { 175 | {"filename", required = true} 176 | } 177 | local filename = cv.argcheck(t, argRules) 178 | 179 | self.ptr = ffi.gc(C.VideoReader_ctorCuda(filename), C.VideoReader_dtorCuda) 180 | end 181 | 182 | function VideoReader:nextFrame(t) 183 | local argRules = { 184 | {"frame", default = nil} 185 | } 186 | local frame = cv.argcheck(t, argRules) 187 | 188 | return cv.unwrap_tensors(C.VideoReader_nextFrameCuda(cv.cuda._info(), 189 | self.ptr, cv.wrap_tensor(frame))) 190 | end 191 | 192 | function VideoReader:format() 193 | return C.VideoReader_formatCuda(self.ptr) 194 | end 195 | end 196 | 197 | return cv.cuda 198 | -------------------------------------------------------------------------------- /include/ximgproc.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | extern "C" 6 | struct TensorWrapper niBlackThreshold(struct TensorWrapper src, struct TensorWrapper dst, double maxValue, int type, int blockSize, double delta); 7 | 8 | 9 | // GraphSegmentation 10 | struct GraphSegmentationPtr { 11 | void *ptr; 12 | 13 | inline cv::ximgproc::segmentation::GraphSegmentation * operator->() { return static_cast(ptr); } 14 | inline cv::ximgproc::segmentation::GraphSegmentation * operator*() { return static_cast(ptr); } 15 | inline GraphSegmentationPtr(cv::ximgproc::segmentation::GraphSegmentation *ptr) { this->ptr = ptr; } 16 | }; 17 | 18 | // GraphSegmentation 19 | extern "C" 20 | struct GraphSegmentationPtr GraphSegmentation_ctor(double sigma, float k, int min_size); 21 | 22 | extern "C" 23 | struct TensorWrapper GraphSegmentation_processImage(struct GraphSegmentationPtr ptr, struct TensorWrapper); 24 | 25 | extern "C" 26 | void GraphSegmentation_setSigma(struct GraphSegmentationPtr ptr, double s); 27 | 28 | extern "C" 29 | double GraphSegmentation_getSigma(struct GraphSegmentationPtr ptr); 30 | 31 | extern "C" 32 | void GraphSegmentation_setK(struct GraphSegmentationPtr ptr, float k); 33 | 34 | extern "C" 35 | float GraphSegmentation_getK(struct GraphSegmentationPtr ptr); 36 | 37 | extern "C" 38 | void GraphSegmentation_setMinSize(struct GraphSegmentationPtr ptr, int min_size); 39 | 40 | extern "C" 41 | int GraphSegmentation_getMinSize(struct GraphSegmentationPtr ptr); 42 | 43 | // SuperpixelSLIC 44 | struct SuperpixelSLICPtr { 45 | void *ptr; 46 | 47 | inline cv::ximgproc::SuperpixelSLIC * operator->() { return static_cast(ptr); } 48 | inline cv::ximgproc::SuperpixelSLIC * operator*() { return static_cast(ptr); } 49 | inline SuperpixelSLICPtr(cv::ximgproc::SuperpixelSLIC *ptr) { this->ptr = ptr; } 50 | }; 51 | 52 | extern "C" 53 | struct SuperpixelSLICPtr SuperpixelSLIC_ctor( 54 | struct TensorWrapper image, int algorithm, 55 | int region_size, float ruler); 56 | 57 | extern "C" 58 | int SuperpixelSLIC_getNumberOfSuperpixels(struct SuperpixelSLICPtr ptr); 59 | 60 | extern "C" 61 | void SuperpixelSLIC_iterate(struct SuperpixelSLICPtr ptr, int num_iterations); 62 | 63 | extern "C" 64 | struct TensorWrapper SuperpixelSLIC_getLabels( 65 | struct SuperpixelSLICPtr ptr, struct TensorWrapper labels_out); 66 | 67 | extern "C" 68 | struct TensorWrapper SuperpixelSLIC_getLabelContourMask( 69 | struct SuperpixelSLICPtr ptr, struct TensorWrapper image, bool thick_line); 70 | 71 | extern "C" 72 | void SuperpixelSLIC_enforceLabelConnectivity( 73 | struct SuperpixelSLICPtr ptr, int min_element_size); 74 | 75 | // See #103 and #95 76 | /* 77 | 78 | // SelectiveSearchSegmentationStrategy 79 | struct SelectiveSearchSegmentationStrategyPtr { 80 | void *ptr; 81 | 82 | inline cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy * operator->() { return static_cast(ptr); } 83 | inline cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy * operator*() { return static_cast(ptr); } 84 | inline SelectiveSearchSegmentationStrategyPtr(cv::ximgproc::segmentation::SelectiveSearchSegmentationStrategy *ptr) { this->ptr = ptr; } 85 | }; 86 | 87 | // 88 | // extern "C" 89 | // struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyColor_ctor(); 90 | // 91 | // extern "C" 92 | // struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategySize_ctor(); 93 | // 94 | // extern "C" 95 | // struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyTexture_ctor(); 96 | // 97 | // extern "C" 98 | // struct SelectiveSearchSegmentationStrategyPtr SelectiveSearchSegmentationStrategyFill_ctor(); 99 | // 100 | // extern "C" 101 | // void SelectiveSearchSegmentationStrategy_setImage(struct SelectiveSearchSegmentationStrategyPtr ptr, struct TensorWrapper, struct TensorWrapper, struct TensorWrapper, int); 102 | // 103 | // extern "C" 104 | // float SelectiveSearchSegmentationStrategy_get(int, int); 105 | // 106 | // extern "C" 107 | // void SelectiveSearchSegmentationStrategy_merge(int, int); 108 | 109 | 110 | // MULTIPLE STRTEGY 111 | // 112 | 113 | // SelectiveSearchSegmentation 114 | struct SelectiveSearchSegmentationPtr { 115 | void *ptr; 116 | 117 | inline cv::ximgproc::segmentation::SelectiveSearchSegmentation * operator->() { return static_cast(ptr); } 118 | inline cv::ximgproc::segmentation::SelectiveSearchSegmentation * operator*() { return static_cast(ptr); } 119 | inline SelectiveSearchSegmentationPtr(cv::ximgproc::segmentation::SelectiveSearchSegmentation *ptr) { this->ptr = ptr; } 120 | }; 121 | 122 | extern "C" 123 | struct SelectiveSearchSegmentationPtr SelectiveSearchSegmentation_ctor(); 124 | 125 | extern "C" 126 | void SelectiveSearchSegmentation_setBaseImage(struct SelectiveSearchSegmentationPtr ptr, struct TensorWrapper); 127 | 128 | extern "C" 129 | void SelectiveSearchSegmentation_switchToSingleStrategy(struct SelectiveSearchSegmentationPtr ptr, int, float); 130 | 131 | extern "C" 132 | void SelectiveSearchSegmentation_switchToSelectiveSearchFast(struct SelectiveSearchSegmentationPtr ptr, int, int, float); 133 | 134 | extern "C" 135 | void SelectiveSearchSegmentation_switchToSelectiveSearchQuality(struct SelectiveSearchSegmentationPtr ptr, int, int, float); 136 | 137 | extern "C" 138 | void SelectiveSearchSegmentation_addImage(struct SelectiveSearchSegmentationPtr ptr, struct TensorWrapper); 139 | 140 | extern "C" 141 | void SelectiveSearchSegmentation_clearImages(struct SelectiveSearchSegmentationPtr ptr); 142 | 143 | extern "C" 144 | void SelectiveSearchSegmentation_addGraphSegmentation(struct SelectiveSearchSegmentationPtr ptr, struct GraphSegmentationPtr); 145 | 146 | extern "C" 147 | void SelectiveSearchSegmentation_clearGraphSegmentations(struct SelectiveSearchSegmentationPtr ptr); 148 | 149 | extern "C" 150 | void SelectiveSearchSegmentation_addStrategy(struct SelectiveSearchSegmentationPtr ptr, struct SelectiveSearchSegmentationStrategyPtr); 151 | 152 | extern "C" 153 | void SelectiveSearchSegmentation_clearStrategies(struct SelectiveSearchSegmentationPtr ptr); 154 | 155 | extern "C" 156 | struct RectArray SelectiveSearchSegmentation_process(struct SelectiveSearchSegmentationPtr ptr); 157 | */ -------------------------------------------------------------------------------- /src/cudawarping.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | extern "C" 4 | struct TensorWrapper remapCuda(struct cutorchInfo info, 5 | struct TensorWrapper src, struct TensorWrapper map1, 6 | struct TensorWrapper map2, int interpolation, struct TensorWrapper dst, 7 | int borderMode, struct ScalarWrapper borderValue) 8 | { 9 | if (dst.isNull()) { 10 | cuda::GpuMat retval; 11 | cuda::remap(src.toGpuMat(), retval, map1.toGpuMat(), map2.toGpuMat(), 12 | interpolation, borderMode, borderValue, prepareStream(info)); 13 | return TensorWrapper(retval, info.state); 14 | } else if (dst.tensorPtr == src.tensorPtr) { 15 | // in-place 16 | cuda::GpuMat source = src.toGpuMat(); 17 | cuda::remap(source, source, map1.toGpuMat(), map2.toGpuMat(), interpolation, 18 | borderMode, borderValue, prepareStream(info)); 19 | } else { 20 | cuda::remap(src.toGpuMat(), dst.toGpuMat(), map1.toGpuMat(), map2.toGpuMat(), 21 | interpolation, borderMode, borderValue, prepareStream(info)); 22 | } 23 | return dst; 24 | } 25 | 26 | extern "C" 27 | struct TensorWrapper resizeCuda(struct cutorchInfo info, 28 | struct TensorWrapper src, struct TensorWrapper dst, 29 | struct SizeWrapper dsize, double fx, double fy, 30 | int interpolation) 31 | { 32 | GpuMatT dstMat = dst.toGpuMatT(); 33 | cuda::resize(src.toGpuMat(), dstMat, dsize, fx, fy, interpolation, prepareStream(info)); 34 | return TensorWrapper(dstMat, info.state); 35 | } 36 | 37 | 38 | extern "C" 39 | struct TensorWrapper warpAffineCuda(struct cutorchInfo info, 40 | struct TensorWrapper src, struct TensorWrapper dst, 41 | struct TensorWrapper M, struct SizeWrapper dsize, 42 | int flags, int borderMode, struct ScalarWrapper borderValue) 43 | { 44 | if (dst.isNull()) { 45 | cuda::GpuMat retval; 46 | cuda::warpAffine(src.toGpuMat(), retval, M.toMat(), dsize, flags, 47 | borderMode, borderValue, prepareStream(info)); 48 | return TensorWrapper(retval, info.state); 49 | } else if (dst.tensorPtr == src.tensorPtr) { 50 | // in-place 51 | cuda::GpuMat source = src.toGpuMat(); 52 | cuda::warpAffine(source, source, M.toMat(), dsize, flags, borderMode, 53 | borderValue, prepareStream(info)); 54 | } else { 55 | cuda::warpAffine(src.toGpuMat(), dst.toGpuMat(), M.toMat(), dsize, 56 | flags, borderMode, borderValue, prepareStream(info)); 57 | } 58 | return dst; 59 | } 60 | 61 | extern "C" 62 | struct TensorArray buildWarpAffineMapsCuda( 63 | struct cutorchInfo info, struct TensorWrapper M, bool inverse, 64 | struct SizeWrapper dsize, struct TensorWrapper xmap, struct TensorWrapper ymap) 65 | { 66 | std::vector retval(2); 67 | retval[0] = xmap.toGpuMat(); 68 | retval[1] = ymap.toGpuMat(); 69 | 70 | cuda::buildWarpAffineMaps(M.toGpuMat(), inverse, dsize, 71 | retval[0], retval[1], prepareStream(info)); 72 | 73 | return TensorArray(retval, info.state); 74 | } 75 | 76 | extern "C" 77 | struct TensorWrapper warpPerspectiveCuda(struct cutorchInfo info, 78 | struct TensorWrapper src, struct TensorWrapper dst, 79 | struct TensorWrapper M, struct SizeWrapper dsize, 80 | int flags, int borderMode, struct ScalarWrapper borderValue) 81 | { 82 | if (dst.isNull()) { 83 | cuda::GpuMat retval; 84 | cuda::warpPerspective(src.toGpuMat(), retval, M.toMat(), dsize, 85 | flags, borderMode, borderValue, prepareStream(info)); 86 | return TensorWrapper(retval, info.state); 87 | } else if (dst.tensorPtr == src.tensorPtr) { 88 | // in-place 89 | cuda::GpuMat source = src.toGpuMat(); 90 | cuda::warpPerspective(source, source, M.toMat(), dsize, flags, 91 | borderMode, borderValue, prepareStream(info)); 92 | } else { 93 | cuda::warpPerspective(src.toGpuMat(), dst.toGpuMat(), M.toMat(), 94 | dsize, flags, borderMode, borderValue, prepareStream(info)); 95 | } 96 | return dst; 97 | } 98 | 99 | extern "C" 100 | struct TensorArray buildWarpPerspectiveMapsCuda( 101 | struct cutorchInfo info, struct TensorWrapper M, bool inverse, 102 | struct SizeWrapper dsize, struct TensorWrapper xmap, struct TensorWrapper ymap) 103 | { 104 | std::vector retval(2); 105 | retval[0] = xmap.toGpuMat(); 106 | retval[1] = ymap.toGpuMat(); 107 | 108 | cuda::buildWarpPerspectiveMaps(M.toGpuMat(), inverse, dsize, 109 | retval[0], retval[1], prepareStream(info)); 110 | 111 | return TensorArray(retval, info.state); 112 | } 113 | 114 | extern "C" 115 | struct TensorWrapper rotateCuda( 116 | struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst, 117 | struct SizeWrapper dsize, double angle, double xShift, double yShift, int interpolation) 118 | { 119 | cuda::GpuMat dstMat = dst.toGpuMat(); 120 | cuda::rotate(src.toGpuMat(), dstMat, dsize, angle, xShift, yShift, 121 | interpolation, prepareStream(info)); 122 | return TensorWrapper(dstMat, info.state); 123 | } 124 | 125 | extern "C" 126 | struct TensorWrapper pyrDownCuda(struct cutorchInfo info, 127 | struct TensorWrapper src, struct TensorWrapper dst) 128 | { 129 | if (dst.isNull()) { 130 | cuda::GpuMat retval; 131 | cuda::pyrDown(src.toGpuMat(), retval, prepareStream(info)); 132 | return TensorWrapper(retval, info.state); 133 | } else if (dst.tensorPtr == src.tensorPtr) { 134 | // in-place 135 | cuda::GpuMat source = src.toGpuMat(); 136 | cuda::pyrDown(source, source, prepareStream(info)); 137 | } else { 138 | cuda::pyrDown(src.toGpuMat(), dst.toGpuMat(), prepareStream(info)); 139 | } 140 | return dst; 141 | } 142 | 143 | extern "C" 144 | struct TensorWrapper pyrUpCuda(struct cutorchInfo info, 145 | struct TensorWrapper src, struct TensorWrapper dst) 146 | { 147 | if (dst.isNull()) { 148 | cuda::GpuMat retval; 149 | cuda::pyrUp(src.toGpuMat(), retval, prepareStream(info)); 150 | return TensorWrapper(retval, info.state); 151 | } else if (dst.tensorPtr == src.tensorPtr) { 152 | // in-place 153 | cuda::GpuMat source = src.toGpuMat(); 154 | cuda::pyrUp(source, source, prepareStream(info)); 155 | } else { 156 | cuda::pyrUp(src.toGpuMat(), dst.toGpuMat(), prepareStream(info)); 157 | } 158 | return dst; 159 | } 160 | -------------------------------------------------------------------------------- /include/cudafeatures2d.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // DescriptorMatcher 6 | 7 | struct DescriptorMatcherPtr { 8 | void *ptr; 9 | inline cuda::DescriptorMatcher * operator->() { return static_cast(ptr); } 10 | inline DescriptorMatcherPtr(cuda::DescriptorMatcher *ptr) { this->ptr = ptr; } 11 | inline cuda::DescriptorMatcher & operator*() { return *static_cast(this->ptr); } 12 | }; 13 | 14 | // Feature2DAsync 15 | 16 | struct Feature2DAsyncPtr { 17 | void *ptr; 18 | inline cuda::Feature2DAsync * operator->() { return static_cast(ptr); } 19 | inline Feature2DAsyncPtr(cuda::Feature2DAsync *ptr) { this->ptr = ptr; } 20 | inline cuda::Feature2DAsync & operator*() { return *static_cast(this->ptr); } 21 | }; 22 | 23 | // FastFeatureDetector 24 | 25 | struct FastFeatureDetectorPtr { 26 | void *ptr; 27 | inline cuda::FastFeatureDetector * operator->() { return static_cast(ptr); } 28 | inline FastFeatureDetectorPtr(cuda::FastFeatureDetector *ptr) { this->ptr = ptr; } 29 | inline cuda::FastFeatureDetector & operator*() { return *static_cast(this->ptr); } 30 | }; 31 | 32 | // ORB 33 | 34 | struct ORBPtr { 35 | void *ptr; 36 | inline cuda::ORB * operator->() { return static_cast(ptr); } 37 | inline ORBPtr(cuda::ORB *ptr) { this->ptr = ptr; } 38 | inline cuda::ORB & operator*() { return *static_cast(this->ptr); } 39 | }; 40 | 41 | extern "C" 42 | struct DescriptorMatcherPtr createBFMatcherCuda(int normType); 43 | 44 | extern "C" 45 | bool DescriptorMatcher_isMaskSupportedCuda(struct DescriptorMatcherPtr ptr); 46 | 47 | extern "C" 48 | void DescriptorMatcher_addCuda( 49 | struct DescriptorMatcherPtr ptr, struct TensorArray descriptors); 50 | 51 | extern "C" 52 | struct TensorArray DescriptorMatcher_getTrainDescriptorsCuda( 53 | struct cutorchInfo info, struct DescriptorMatcherPtr ptr); 54 | 55 | extern "C" 56 | void DescriptorMatcher_clearCuda(struct DescriptorMatcherPtr ptr); 57 | 58 | extern "C" 59 | bool DescriptorMatcher_emptyCuda(struct DescriptorMatcherPtr ptr); 60 | 61 | extern "C" 62 | void DescriptorMatcher_trainCuda(struct DescriptorMatcherPtr ptr); 63 | 64 | extern "C" 65 | struct TensorWrapper DescriptorMatcher_matchCuda( 66 | struct cutorchInfo info, struct DescriptorMatcherPtr ptr, 67 | struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, 68 | struct TensorWrapper matches, struct TensorWrapper mask); 69 | 70 | extern "C" 71 | struct TensorWrapper DescriptorMatcher_match_masksCuda( 72 | struct cutorchInfo info, struct DescriptorMatcherPtr ptr, 73 | struct TensorWrapper queryDescriptors, struct TensorWrapper matches, 74 | struct TensorArray masks); 75 | 76 | extern "C" 77 | struct DMatchArray DescriptorMatcher_matchConvertCuda( 78 | struct DescriptorMatcherPtr ptr, struct TensorWrapper gpu_matches); 79 | 80 | extern "C" 81 | struct TensorWrapper DescriptorMatcher_knnMatchCuda( 82 | struct cutorchInfo info, struct DescriptorMatcherPtr ptr, 83 | struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, 84 | struct TensorWrapper matches, int k, struct TensorWrapper mask); 85 | 86 | extern "C" 87 | struct TensorWrapper DescriptorMatcher_knnMatch_masksCuda( 88 | struct cutorchInfo info, struct DescriptorMatcherPtr ptr, 89 | struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, 90 | struct TensorWrapper matches, int k, struct TensorArray masks); 91 | 92 | extern "C" 93 | struct DMatchArrayOfArrays DescriptorMatcher_knnMatchConvertCuda( 94 | struct DescriptorMatcherPtr ptr, 95 | struct TensorWrapper gpu_matches, bool compactResult); 96 | 97 | extern "C" 98 | struct TensorWrapper DescriptorMatcher_radiusMatchCuda( 99 | struct cutorchInfo info, struct DescriptorMatcherPtr ptr, 100 | struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, 101 | struct TensorWrapper matches, float maxDistance, struct TensorWrapper mask); 102 | 103 | extern "C" 104 | struct TensorWrapper DescriptorMatcher_radiusMatch_masksCuda( 105 | struct cutorchInfo info, struct DescriptorMatcherPtr ptr, 106 | struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, 107 | struct TensorWrapper matches, float maxDistance, struct TensorArray masks); 108 | 109 | extern "C" 110 | struct DMatchArrayOfArrays DescriptorMatcher_radiusMatchConvertCuda( 111 | struct DescriptorMatcherPtr ptr, 112 | struct TensorWrapper gpu_matches, bool compactResult); 113 | 114 | extern "C" 115 | void Feature2DAsync_dtorCuda(struct Feature2DAsyncPtr ptr); 116 | 117 | extern "C" 118 | struct TensorWrapper Feature2DAsync_detectAsyncCuda( 119 | struct cutorchInfo info, struct Feature2DAsyncPtr ptr, struct TensorWrapper image, 120 | struct TensorWrapper keypoints, struct TensorWrapper mask); 121 | 122 | extern "C" 123 | struct TensorArray Feature2DAsync_computeAsyncCuda( 124 | struct cutorchInfo info, struct Feature2DAsyncPtr ptr, struct TensorWrapper image, 125 | struct TensorWrapper keypoints, struct TensorWrapper descriptors); 126 | 127 | extern "C" 128 | struct TensorArray Feature2DAsync_detectAndComputeAsyncCuda( 129 | struct cutorchInfo info, struct Feature2DAsyncPtr ptr, struct TensorWrapper image, 130 | struct TensorWrapper mask, struct TensorWrapper keypoints, 131 | struct TensorWrapper descriptors, bool useProvidedKeypoints); 132 | 133 | extern "C" 134 | struct KeyPointArray Feature2DAsync_convertCuda( 135 | struct Feature2DAsyncPtr ptr, struct TensorWrapper gpu_keypoints); 136 | 137 | extern "C" 138 | struct FastFeatureDetectorPtr FastFeatureDetector_ctorCuda( 139 | int threshold, bool nonmaxSuppression, int type, int max_npoints); 140 | 141 | extern "C" 142 | void FastFeatureDetector_dtorCuda(struct FastFeatureDetectorPtr ptr); 143 | 144 | extern "C" 145 | void FastFeatureDetector_setMaxNumPointsCuda(struct FastFeatureDetectorPtr ptr, int val); 146 | 147 | extern "C" 148 | int FastFeatureDetector_getMaxNumPointsCuda(struct FastFeatureDetectorPtr ptr); 149 | 150 | extern "C" 151 | struct ORBPtr ORB_ctorCuda( 152 | int nfeatures, float scaleFactor, int nlevels, int edgeThreshold, int firstLevel, 153 | int WTA_K, int scoreType, int patchSize, int fastThreshold, bool blurForDescriptor); 154 | 155 | extern "C" 156 | void ORB_setBlurForDescriptorCuda(struct ORBPtr ptr, bool val); 157 | 158 | extern "C" 159 | bool ORB_getBlurForDescriptorCuda(struct ORBPtr ptr); 160 | -------------------------------------------------------------------------------- /cv/videoio/init.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv._env' 2 | 3 | local ffi = require 'ffi' 4 | 5 | local C = ffi.load(cv.libPath('videoio')) 6 | 7 | --- ***************** Classes ***************** 8 | require 'cv.Classes' 9 | 10 | -- VideoCapture 11 | 12 | ffi.cdef[[ 13 | struct PtrWrapper VideoCapture_ctor_default(); 14 | 15 | struct PtrWrapper VideoCapture_ctor_device(int device); 16 | 17 | struct PtrWrapper VideoCapture_ctor_filename(const char *filename); 18 | 19 | void VideoCapture_dtor(struct PtrWrapper ptr); 20 | 21 | bool VideoCapture_open(struct PtrWrapper ptr, int device); 22 | 23 | bool VideoCapture_isOpened(struct PtrWrapper ptr); 24 | 25 | void VideoCapture_release(struct PtrWrapper ptr); 26 | 27 | bool VideoCapture_grab(struct PtrWrapper ptr); 28 | 29 | struct TensorPlusBool VideoCapture_retrieve( 30 | struct PtrWrapper ptr, struct TensorWrapper image, int flag); 31 | 32 | struct TensorPlusBool VideoCapture_read( 33 | struct PtrWrapper ptr, struct TensorWrapper image); 34 | 35 | bool VideoCapture_set(struct PtrWrapper ptr, int propId, double value); 36 | 37 | double VideoCapture_get(struct PtrWrapper ptr, int propId); 38 | ]] 39 | 40 | do 41 | local VideoCapture = torch.class('cv.VideoCapture', cv) 42 | 43 | -- v = cv.VideoCapture{} 44 | -- OR 45 | -- v = cv.VideoCapture{filename='../video.mp4'} 46 | -- OR 47 | -- v = cv.VideoCapture{device=2} 48 | function VideoCapture:__init(t) 49 | if type(t.filename or t[1]) == 'string' then 50 | self.ptr = ffi.gc(C.VideoCapture_ctor_filename(t.filename or t[1]), C.VideoCapture_dtor) 51 | elseif type(t.device or t[1]) == 'number' then 52 | self.ptr = ffi.gc(C.VideoCapture_ctor_device(t.device or t[1]), C.VideoCapture_dtor) 53 | else 54 | self.ptr = ffi.gc(C.VideoCapture_ctor_default(), C.VideoCapture_dtor) 55 | end 56 | end 57 | 58 | function VideoCapture:open(t) 59 | local argRules = { 60 | {"device", required = true} 61 | } 62 | local device = cv.argcheck(t, argRules) 63 | 64 | return C.VideoCapture_open(self.ptr, device) 65 | end 66 | 67 | function VideoCapture:isOpened() 68 | return C.VideoCapture_isOpened(self.ptr) 69 | end 70 | 71 | function VideoCapture:release() 72 | C.VideoCapture_release(self.ptr) 73 | end 74 | 75 | function VideoCapture:grab() 76 | return C.VideoCapture_grab(self.ptr) 77 | end 78 | 79 | function VideoCapture:retrieve(t) 80 | local argRules = { 81 | {"image", default = nil}, 82 | {"flag", default = 0} 83 | } 84 | local image, flag = cv.argcheck(t, argRules) 85 | 86 | result = C.VideoCapture_retrieve(self.ptr, cv.wrap_tensor(image), flag) 87 | return result.val, cv.unwrap_tensors(result.tensor) 88 | end 89 | 90 | -- result, image = cap.read{} 91 | -- OR 92 | -- im = torch.FloatTensor(640, 480, 3) 93 | -- result = cap.read{image=image} 94 | function VideoCapture:read(t) 95 | local argRules = { 96 | {"image", default = nil} 97 | } 98 | local image = cv.argcheck(t, argRules) 99 | 100 | result = C.VideoCapture_read(self.ptr, cv.wrap_tensor(image)) 101 | return result.val, cv.unwrap_tensors(result.tensor) 102 | end 103 | 104 | function VideoCapture:set(t) 105 | local argRules = { 106 | {"propId", required = true}, 107 | {"value", required = true} 108 | } 109 | local propId, value = cv.argcheck(t, argRules) 110 | 111 | return C.VideoCapture_set(self.ptr, propId, value) 112 | end 113 | 114 | function VideoCapture:get(t) 115 | local argRules = { 116 | {"propId", required = true} 117 | } 118 | local propId = cv.argcheck(t, argRules) 119 | 120 | return C.VideoCapture_get(self.ptr, propId) 121 | end 122 | end 123 | 124 | -- VideoWriter 125 | 126 | ffi.cdef[[ 127 | struct PtrWrapper VideoWriter_ctor_default(); 128 | 129 | struct PtrWrapper VideoWriter_ctor( 130 | const char *filename, int fourcc, double fps, struct SizeWrapper frameSize, bool isColor); 131 | 132 | void VideoWriter_dtor(struct PtrWrapper ptr); 133 | 134 | bool VideoWriter_open(struct PtrWrapper ptr, const char *filename, int fourcc, 135 | double fps, struct SizeWrapper frameSize, bool isColor); 136 | 137 | bool VideoWriter_isOpened(struct PtrWrapper ptr); 138 | 139 | void VideoWriter_release(struct PtrWrapper ptr); 140 | 141 | void VideoWriter_write(struct PtrWrapper ptr, struct TensorWrapper image); 142 | 143 | bool VideoWriter_set(struct PtrWrapper ptr, int propId, double value); 144 | 145 | double VideoWriter_get(struct PtrWrapper ptr, int propId); 146 | 147 | int VideoWriter_fourcc(char c1, char c2, char c3, char c4); 148 | ]] 149 | 150 | do 151 | local VideoWriter = torch.class('cv.VideoWriter', cv) 152 | 153 | function VideoWriter:__init(t) 154 | local argRules = { 155 | {"filename", required = true}, 156 | {"fourcc", required = true}, 157 | {"fps", required = true}, 158 | {"frameSize", required = true, operator = cv.Size}, 159 | {"isColor", default = true} 160 | } 161 | local filename, fourcc, fps, frameSize, isColor = cv.argcheck(t, argRules) 162 | if t.filename or t[1] then 163 | self.ptr = ffi.gc(C.VideoWriter_ctor( 164 | filename, fourcc, fps, frameSize, isColor), 165 | C.VideoWriter_dtor) 166 | else 167 | self.ptr = ffi.gc(C.VideoWriter_ctor_default(), C.VideoWriter_dtor) 168 | end 169 | end 170 | 171 | function VideoWriter:open(t) 172 | local argRules = { 173 | {"filename", required = true}, 174 | {"fourcc", required = true}, 175 | {"fps", required = true}, 176 | {"frameSize", required = true, operator = cv.Size}, 177 | {"isColor", default = nil} 178 | } 179 | local filename, fourcc, fps, frameSize, isColor = cv.argcheck(t, argRules) 180 | if isColor == nil then isColor = true end 181 | 182 | return C.VideoWriter_open(self.ptr, filename, fourcc, fps, frameSize, isColor) 183 | end 184 | 185 | function VideoWriter:isOpened() 186 | return C.VideoWriter_isOpened(self.ptr) 187 | end 188 | 189 | function VideoWriter:release() 190 | C.VideoWriter_release(self.ptr) 191 | end 192 | 193 | function VideoWriter:write(t) 194 | local argRules = { 195 | {"image", required = true} 196 | } 197 | local image = cv.argcheck(t, argRules) 198 | C.VideoWriter_write(self.ptr, cv.wrap_tensor(image)) 199 | end 200 | 201 | function VideoWriter:set(t) 202 | local argRules = { 203 | {"propId", required = true}, 204 | {"value", required = true} 205 | } 206 | local propId, value = cv.argcheck(t, argRules) 207 | 208 | return C.VideoWriter_set(self.ptr, propId, value) 209 | end 210 | 211 | function VideoWriter:get(t) 212 | local argRules = { 213 | {"propId", required = true} 214 | } 215 | local propId = cv.argcheck(t, argRules) 216 | 217 | return C.VideoWriter_get(self.ptr, propId) 218 | end 219 | 220 | function VideoWriter.fourcc(t) 221 | local argRules = { 222 | {"c1", required = true}, 223 | {"c2", required = true}, 224 | {"c3", required = true}, 225 | {"c4", required = true} 226 | } 227 | local c1, c2, c3, c4 = cv.argcheck(t, argRules) 228 | 229 | return C.VideoWriter_fourcc(string.byte(c1), string.byte(c2), string.byte(c3), string.byte(c4)) 230 | end 231 | end 232 | 233 | return cv 234 | -------------------------------------------------------------------------------- /src/cudabgsegm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | extern "C" 4 | struct BackgroundSubtractorMOGPtr BackgroundSubtractorMOG_ctorCuda( 5 | int History, int NMixtures, double BackgroundRatio, double NoiseSigma) 6 | { 7 | return rescueObjectFromPtr(cuda::createBackgroundSubtractorMOG( 8 | History, NMixtures, BackgroundRatio, NoiseSigma)); 9 | } 10 | 11 | extern "C" 12 | struct TensorWrapper BackgroundSubtractorMOG_applyCuda(struct cutorchInfo info, 13 | struct BackgroundSubtractorMOGPtr ptr, struct TensorWrapper image, 14 | struct TensorWrapper fgmask, double learningRate) 15 | { 16 | cuda::GpuMat retval = fgmask.toGpuMat(); 17 | ptr->apply(image.toGpuMat(), retval, learningRate, prepareStream(info)); 18 | return TensorWrapper(retval, info.state); 19 | } 20 | 21 | extern "C" 22 | struct TensorWrapper BackgroundSubtractorMOG_getBackgroundImageCuda( 23 | struct cutorchInfo info, struct BackgroundSubtractorMOGPtr ptr, 24 | struct TensorWrapper backgroundImage) 25 | { 26 | cuda::GpuMat retval = backgroundImage.toGpuMat(); 27 | ptr->getBackgroundImage(retval, prepareStream(info)); 28 | return TensorWrapper(retval, info.state); 29 | } 30 | 31 | extern "C" 32 | void BackgroundSubtractorMOG_setHistoryCuda(struct BackgroundSubtractorMOGPtr ptr, int val) 33 | { 34 | ptr->setHistory(val); 35 | } 36 | 37 | extern "C" 38 | int BackgroundSubtractorMOG_getHistoryCuda(struct BackgroundSubtractorMOGPtr ptr) 39 | { 40 | return ptr->getHistory(); 41 | } 42 | 43 | extern "C" 44 | void BackgroundSubtractorMOG_setNMixturesCuda(struct BackgroundSubtractorMOGPtr ptr, int val) 45 | { 46 | ptr->setNMixtures(val); 47 | } 48 | 49 | extern "C" 50 | int BackgroundSubtractorMOG_getNMixturesCuda(struct BackgroundSubtractorMOGPtr ptr) 51 | { 52 | return ptr->getNMixtures(); 53 | } 54 | 55 | extern "C" 56 | void BackgroundSubtractorMOG_setBackgroundRatioCuda(struct BackgroundSubtractorMOGPtr ptr, double val) 57 | { 58 | ptr->setBackgroundRatio(val); 59 | } 60 | 61 | extern "C" 62 | double BackgroundSubtractorMOG_getBackgroundRatioCuda(struct BackgroundSubtractorMOGPtr ptr) 63 | { 64 | return ptr->getBackgroundRatio(); 65 | } 66 | 67 | extern "C" 68 | void BackgroundSubtractorMOG_setNoiseSigmaCuda(struct BackgroundSubtractorMOGPtr ptr, double val) 69 | { 70 | ptr->setNoiseSigma(val); 71 | } 72 | 73 | extern "C" 74 | double BackgroundSubtractorMOG_getNoiseSigmaCuda(struct BackgroundSubtractorMOGPtr ptr) 75 | { 76 | return ptr->getNoiseSigma(); 77 | } 78 | 79 | extern "C" 80 | struct BackgroundSubtractorMOG2Ptr BackgroundSubtractorMOG2_ctorCuda( 81 | int history, double varThreshold, bool detectShadows) 82 | { 83 | return rescueObjectFromPtr(cuda::createBackgroundSubtractorMOG2( 84 | history, varThreshold, detectShadows)); 85 | } 86 | 87 | extern "C" 88 | struct TensorWrapper BackgroundSubtractorMOG2_applyCuda(struct cutorchInfo info, 89 | struct BackgroundSubtractorMOG2Ptr ptr, struct TensorWrapper image, 90 | struct TensorWrapper fgmask, double learningRate) 91 | { 92 | cuda::GpuMat retval = fgmask.toGpuMat(); 93 | ptr->apply(image.toGpuMat(), retval, learningRate, prepareStream(info)); 94 | return TensorWrapper(retval, info.state); 95 | } 96 | 97 | extern "C" 98 | struct TensorWrapper BackgroundSubtractorMOG2_getBackgroundImageCuda( 99 | struct cutorchInfo info, struct BackgroundSubtractorMOG2Ptr ptr, 100 | struct TensorWrapper backgroundImage) 101 | { 102 | cuda::GpuMat retval = backgroundImage.toGpuMat(); 103 | ptr->getBackgroundImage(retval, prepareStream(info)); 104 | return TensorWrapper(retval, info.state); 105 | } 106 | 107 | extern "C" 108 | int BackgroundSubtractorMOG2_getHistoryCuda(struct BackgroundSubtractorMOG2Ptr ptr) 109 | { 110 | return ptr->getHistory(); 111 | } 112 | 113 | extern "C" 114 | void BackgroundSubtractorMOG2_setHistoryCuda(struct BackgroundSubtractorMOG2Ptr ptr, int history) 115 | { 116 | ptr->setHistory(history); 117 | } 118 | 119 | extern "C" 120 | int BackgroundSubtractorMOG2_getNMixturesCuda(struct BackgroundSubtractorMOG2Ptr ptr) 121 | { 122 | return ptr->getNMixtures(); 123 | } 124 | 125 | extern "C" 126 | void BackgroundSubtractorMOG2_setNMixturesCuda(struct BackgroundSubtractorMOG2Ptr ptr, int nmixtures) 127 | { 128 | ptr->setNMixtures(nmixtures); 129 | } 130 | 131 | extern "C" 132 | int BackgroundSubtractorMOG2_getShadowValueCuda(struct BackgroundSubtractorMOG2Ptr ptr) 133 | { 134 | return ptr->getShadowValue(); 135 | } 136 | 137 | extern "C" 138 | void BackgroundSubtractorMOG2_setShadowValueCuda(struct BackgroundSubtractorMOG2Ptr ptr, int shadow_value) 139 | { 140 | ptr->setShadowValue(shadow_value); 141 | } 142 | 143 | extern "C" 144 | double BackgroundSubtractorMOG2_getBackgroundRatioCuda(struct BackgroundSubtractorMOG2Ptr ptr) 145 | { 146 | return ptr->getBackgroundRatio(); 147 | } 148 | 149 | extern "C" 150 | void BackgroundSubtractorMOG2_setBackgroundRatioCuda(struct BackgroundSubtractorMOG2Ptr ptr, double ratio) 151 | { 152 | ptr->setBackgroundRatio(ratio); 153 | } 154 | 155 | extern "C" 156 | double BackgroundSubtractorMOG2_getVarThresholdCuda(struct BackgroundSubtractorMOG2Ptr ptr) 157 | { 158 | return ptr->getVarThreshold(); 159 | } 160 | 161 | extern "C" 162 | void BackgroundSubtractorMOG2_setVarThresholdCuda(struct BackgroundSubtractorMOG2Ptr ptr, double varThreshold) 163 | { 164 | ptr->setVarThreshold(varThreshold); 165 | } 166 | 167 | extern "C" 168 | double BackgroundSubtractorMOG2_getVarThresholdGenCuda(struct BackgroundSubtractorMOG2Ptr ptr) 169 | { 170 | return ptr->getVarThresholdGen(); 171 | } 172 | 173 | extern "C" 174 | void BackgroundSubtractorMOG2_setVarThresholdGenCuda(struct BackgroundSubtractorMOG2Ptr ptr, double varThresholdGen) 175 | { 176 | ptr->setVarThresholdGen(varThresholdGen); 177 | } 178 | 179 | extern "C" 180 | double BackgroundSubtractorMOG2_getVarInitCuda(struct BackgroundSubtractorMOG2Ptr ptr) 181 | { 182 | return ptr->getVarInit(); 183 | } 184 | 185 | extern "C" 186 | void BackgroundSubtractorMOG2_setVarInitCuda(struct BackgroundSubtractorMOG2Ptr ptr, double varInit) 187 | { 188 | ptr->setVarInit(varInit); 189 | } 190 | 191 | extern "C" 192 | double BackgroundSubtractorMOG2_getVarMinCuda(struct BackgroundSubtractorMOG2Ptr ptr) 193 | { 194 | return ptr->getVarMin(); 195 | } 196 | 197 | extern "C" 198 | void BackgroundSubtractorMOG2_setVarMinCuda(struct BackgroundSubtractorMOG2Ptr ptr, double varMin) 199 | { 200 | ptr->setVarMin(varMin); 201 | } 202 | 203 | extern "C" 204 | double BackgroundSubtractorMOG2_getVarMaxCuda(struct BackgroundSubtractorMOG2Ptr ptr) 205 | { 206 | return ptr->getVarMax(); 207 | } 208 | 209 | extern "C" 210 | void BackgroundSubtractorMOG2_setVarMaxCuda(struct BackgroundSubtractorMOG2Ptr ptr, double varMax) 211 | { 212 | ptr->setVarMax(varMax); 213 | } 214 | 215 | extern "C" 216 | bool BackgroundSubtractorMOG2_getDetectShadowsCuda(struct BackgroundSubtractorMOG2Ptr ptr) 217 | { 218 | return ptr->getDetectShadows(); 219 | } 220 | 221 | extern "C" 222 | void BackgroundSubtractorMOG2_setDetectShadowsCuda(struct BackgroundSubtractorMOG2Ptr ptr, bool detectShadows) 223 | { 224 | ptr->setDetectShadows(detectShadows); 225 | } 226 | 227 | extern "C" 228 | double BackgroundSubtractorMOG2_getComplexityReductionThresholdCuda(struct BackgroundSubtractorMOG2Ptr ptr) 229 | { 230 | return ptr->getComplexityReductionThreshold(); 231 | } 232 | 233 | extern "C" 234 | void BackgroundSubtractorMOG2_setComplexityReductionThresholdCuda(struct BackgroundSubtractorMOG2Ptr ptr, double ct) 235 | { 236 | ptr->setComplexityReductionThreshold(ct); 237 | } 238 | 239 | extern "C" 240 | double BackgroundSubtractorMOG2_getShadowThresholdCuda(struct BackgroundSubtractorMOG2Ptr ptr) 241 | { 242 | return ptr->getShadowThreshold(); 243 | } 244 | 245 | extern "C" 246 | void BackgroundSubtractorMOG2_setShadowThresholdCuda(struct BackgroundSubtractorMOG2Ptr ptr, double shadowThreshold) 247 | { 248 | ptr->setShadowThreshold(shadowThreshold); 249 | } 250 | -------------------------------------------------------------------------------- /cv/highgui/init.lua: -------------------------------------------------------------------------------- 1 | local cv = require 'cv._env' 2 | 3 | local ffi = require 'ffi' 4 | 5 | ffi.cdef[[ 6 | typedef void (*MouseCallback)(int event, int x, int y, int flags, void* userdata); 7 | typedef void (*TrackbarCallback)(int pos, void* userdata); 8 | typedef void (*OpenGlDrawCallback)(void* userdata); 9 | typedef void (*ButtonCallback)(int state, void* userdata); 10 | 11 | void imshow(const char *winname, struct TensorWrapper mat); 12 | 13 | int waitKey(int delay); 14 | 15 | void namedWindow(const char *winname, int flags); 16 | 17 | void destroyWindow(const char *winname); 18 | 19 | void destroyAllWindows(); 20 | 21 | int startWindowThread(); 22 | 23 | void resizeWindow(const char *winname, int width, int height); 24 | 25 | void moveWindow(const char *winname, int x, int y); 26 | 27 | void setWindowProperty(const char *winname, int prop_id, double prop_value); 28 | 29 | void setWindowTitle(const char *winname, const char *title); 30 | 31 | double getWindowProperty(const char *winname, int prop_id); 32 | 33 | void setMouseCallback(const char *winname, MouseCallback onMouse, void *userdata); 34 | 35 | int getMouseWheelData(int flags); 36 | 37 | int createTrackbar( 38 | const char *trackbarname, const char *winname, int *value, 39 | int count, TrackbarCallback onChange, void *userdata); 40 | 41 | int getTrackbarPos(const char *trackbarname, const char *winname); 42 | 43 | void setTrackbarPos(const char *trackbarname, const char *winname, int pos); 44 | 45 | void setTrackbarMax(const char *trackbarname, const char *winname, int maxval); 46 | 47 | void updateWindow(const char *winname); 48 | 49 | void displayOverlay(const char *winname, const char *text, int delayms); 50 | 51 | void displayStatusBar(const char *winname, const char *text, int delayms); 52 | 53 | void saveWindowParameters(const char *windowName); 54 | 55 | void loadWindowParameters(const char *windowName); 56 | ]] 57 | 58 | local C = ffi.load(cv.libPath('highgui')) 59 | 60 | function cv.imshow(t) 61 | local argRules = { 62 | {"winname", required = true}, 63 | {"image", required = true} 64 | } 65 | local winname, image = cv.argcheck(t, argRules) 66 | 67 | C.imshow(winname, cv.wrap_tensor(image)) 68 | end 69 | 70 | function cv.waitKey(t) 71 | local argRules = { 72 | {"delay", default = 0} 73 | } 74 | local delay = cv.argcheck(t, argRules) 75 | 76 | return C.waitKey(delay) 77 | end 78 | 79 | function cv.namedWindow(t) 80 | local argRules = { 81 | {"winname", default = "Window 1"}, 82 | {"flags", default = cv.WINDOW_AUTOSIZE} 83 | } 84 | local winname, flags = cv.argcheck(t, argRules) 85 | 86 | C.namedWindow(winname, flags) 87 | end 88 | 89 | function cv.destroyWindow(t) 90 | local argRules = { 91 | {"winname", required = true} 92 | } 93 | local winname = cv.argcheck(t, argRules) 94 | 95 | return C.destroyWindow(winname) 96 | end 97 | 98 | function cv.destroyAllWindows(t) 99 | return C.destroyAllWindows() 100 | end 101 | 102 | function cv.startWindowThread(t) 103 | return C.startWindowThread() 104 | end 105 | 106 | function cv.resizeWindow(t) 107 | local argRules = { 108 | {"winname", required = true}, 109 | {"width", required = true}, 110 | {"height", required = true} 111 | } 112 | local winname, width, height = cv.argcheck(t, argRules) 113 | 114 | return C.resizeWindow(winname, width, height) 115 | end 116 | 117 | function cv.moveWindow(t) 118 | local argRules = { 119 | {"winname", required = true}, 120 | {"x", required = true}, 121 | {"y", required = true} 122 | } 123 | local winname, x, y = cv.argcheck(t, argRules) 124 | 125 | return C.moveWindow(winname, x, y) 126 | end 127 | 128 | function cv.setWindowProperty(t) 129 | local argRules = { 130 | {"winname", required = true}, 131 | {"prop_id", required = true}, 132 | {"prop_value", required = true} 133 | } 134 | local winname, prop_id, prop_value = cv.argcheck(t, argRules) 135 | 136 | return C.setWindowProperty(winname, prop_id, prop_value) 137 | end 138 | 139 | function cv.setWindowTitle(t) 140 | local argRules = { 141 | {"winname", required = true}, 142 | {"title", required = true} 143 | } 144 | local winname, title = cv.argcheck(t, argRules) 145 | 146 | return C.setWindowTitle(winname, title) 147 | end 148 | 149 | function cv.getWindowProperty(t) 150 | local argRules = { 151 | {"winname", required = true}, 152 | {"prop_id", required = true} 153 | } 154 | local winname, prop_id = cv.argcheck(t, argRules) 155 | 156 | return C.getWindowProperty(winname, prop_id) 157 | end 158 | 159 | function cv.setMouseCallback(t) 160 | local argRules = { 161 | {"winname", required = true}, 162 | {"onMouse", required = true}, 163 | {"userdata", default = nil} 164 | } 165 | local winname, onMouse, userdata = cv.argcheck(t, argRules) 166 | 167 | return C.setMouseCallback(winname, onMouse, userdata) 168 | end 169 | 170 | function cv.getMouseWheelData(t) 171 | local argRules = { 172 | {"flags", required = true} 173 | } 174 | local flags = cv.argcheck(t, argRules) 175 | 176 | return C.getMouseWheelData(flags) 177 | end 178 | 179 | function cv.createTrackbar(t) 180 | local argRules = { 181 | {"trackbarname", required = true}, 182 | {"winname", required = true}, 183 | {"value", default = nil}, 184 | {"count", required = true}, 185 | {"onChange", default = nil}, 186 | {"userdata", default = nil} 187 | } 188 | local trackbarname, winname, value, count, onChange, userdata = cv.argcheck(t, argRules) 189 | 190 | return C.createTrackbar(trackbarname, winname, value, count, onChange, userdata) 191 | end 192 | 193 | function cv.getTrackbarPos(t) 194 | local argRules = { 195 | {"trackbarname", required = true}, 196 | {"winname", required = true} 197 | } 198 | local trackbarname, winname = cv.argcheck(t, argRules) 199 | 200 | return C.getTrackbarPos(trackbarname, winname) 201 | end 202 | 203 | function cv.setTrackbarPos(t) 204 | local argRules = { 205 | {"trackbarname", required = true}, 206 | {"winname", required = true}, 207 | {"pos", required = true} 208 | } 209 | local trackbarname, winname, pos = cv.argcheck(t, argRules) 210 | 211 | return C.setTrackbarPos(trackbarname, winname, pos) 212 | end 213 | 214 | function cv.setTrackbarMax(t) 215 | local argRules = { 216 | {"trackbarname", required = true}, 217 | {"winname", required = true}, 218 | {"maxval", required = true} 219 | } 220 | local trackbarname, winname, maxval = cv.argcheck(t, argRules) 221 | 222 | return C.setTrackbarMax(trackbarname, winname, maxval) 223 | end 224 | 225 | function cv.updateWindow(t) 226 | local argRules = { 227 | {"winname", required = true} 228 | } 229 | local winname = cv.argcheck(t, argRules) 230 | 231 | return C.updateWindow(winname) 232 | end 233 | 234 | function cv.displayOverlay(t) 235 | local argRules = { 236 | {"winname", required = true}, 237 | {"text", required = true}, 238 | {"delayms", required = true} 239 | } 240 | local winname, text, delayms = cv.argcheck(t, argRules) 241 | 242 | return C.displayOverlay(winname, text, delayms) 243 | end 244 | 245 | function cv.displayStatusBar(t) 246 | local argRules = { 247 | {"winname", required = true}, 248 | {"text", required = true}, 249 | {"delayms", required = true} 250 | } 251 | local winname, text, delayms = cv.argcheck(t, argRules) 252 | 253 | return C.displayStatusBar(winname, text, delayms) 254 | end 255 | 256 | function cv.saveWindowParameters(t) 257 | local argRules = { 258 | {"windowName", required = true} 259 | } 260 | local windowName = cv.argcheck(t, argRules) 261 | 262 | return C.saveWindowParameters(windowName) 263 | end 264 | 265 | function cv.loadWindowParameters(t) 266 | local argRules = { 267 | {"windowName", required = true} 268 | } 269 | local windowName = cv.argcheck(t, argRules) 270 | 271 | return C.loadWindowParameters(windowName) 272 | end 273 | 274 | return cv 275 | --------------------------------------------------------------------------------