Last active
September 29, 2022 04:55
-
-
Save jaybo/b053a8aa5f7e03196170491dec38e61e to your computer and use it in GitHub Desktop.
Multithreading template matching OpenCV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <opencv2/opencv.hpp> | |
#include <chrono> | |
using namespace std; | |
typedef std::chrono::high_resolution_clock Clock; | |
void threadCallback(GpuMat &imS, GpuMat &imT, int count) | |
{ | |
std::cout << "Start Thread = " << std::this_thread::get_id() << std::endl; | |
GpuMat imR = GpuMat(imS.size().height - imT.size().height + 1, | |
imS.size().width - imT.size().width + 1, CV_8UC1); | |
Ptr<TemplateMatching> pMatcher = cuda::createTemplateMatching(CV_8U, CV_TM_CCORR_NORMED); | |
cuda::Stream stream; | |
for (int j = 0; j < count; j++) { | |
pMatcher->match(imS, imT, imR, stream); | |
} | |
stream.waitForCompletion(); | |
std::cout << "Finished Thread = " << std::this_thread::get_id() << std::endl; | |
} | |
void TestMatchThreads() | |
{ | |
// Does threading improve perf for many matches? | |
Mat im = cv::imread("D:/data/jayb1/000000/0/20190219223436749_jayb1_000000_0_16_0.tif"); | |
GpuMat imT = GpuMat(100, 100, CV_8UC1); | |
GpuMat imS = GpuMat(3840, 3840, CV_8UC1); | |
GpuMat imR = GpuMat(3840, 3840, CV_8UC1); | |
imS.upload(im); | |
Rect rc = cv::Rect(cv::Point(0, 0), imT.size()); | |
Mat temp = im(rc); | |
imT.upload(temp); | |
std::vector< std::thread> threads; | |
int N_THREADS = 3; | |
int count = 10; | |
auto t1 = Clock::now(); | |
for (int j = 0; j < N_THREADS; j++) { | |
std::thread threadObj(threadCallback, imS, imT, count); | |
threads.push_back(std::move(threadObj)); | |
} | |
for (int j = 0; j < N_THREADS; j++) { | |
threads[j].join(); | |
} | |
auto t2 = Clock::now(); | |
std::cout << "elapsed: " | |
<< std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() | |
<< " mS" << std::endl; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Above code gives the error:
OpenCV Error: Assertion failed (allocSize == allocations.back()) in
anonymous-namespace'::MemoryStack::returnMemory, file C:\Users\derrickb\Documents\opencv\modules\core\src\cuda_stream.cpp, line 99`
with 3 or more threads.