# How to use cuda::SparsePyrLKOpticalFlow in multi thread environment

**URL:** <https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632>\
**Category:** C++\
**Tags:** multithreading, cuda, optflow\
**Created:** [July 26, 2022, 6:30am UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632 "2022-07-26T06:30:30Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![keivan\_moazami](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/keivan_moazami/32/5713_2.png) [@keivan\_moazami](https://forum.opencv.org/u/keivan_moazami)\
**Post date:** [July 26, 2022, 6:30am UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632/1 "2022-07-26T06:30:30Z")

</div>

When I using cuda::SparsePyrLKOpticalFlow in multi thread application failed to calc optical flow properly.  
I run it on different cuda::GpuMats and in separate cuda::Streams with separate Algorithm instances.  
I create new instance with cuda::SparsePyrLKOpticalFlow::create() method In each thread but have same problem.

---

<div class="post-metadata">

**Author:** ![cudawarped](https://avatars.discourse-cdn.com/v4/letter/c/9dc877/32.png) [@cudawarped](https://forum.opencv.org/u/cudawarped)\
**Post date:** [July 26, 2022, 12:17pm UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632/2 "2022-07-26T12:17:02Z")

</div>

If you are getting different results when using seperate threads that would point to some global memory usage (this used to be common in functions which called CUDA NPP under the hood). The other possibility could be that you are not calling `waitForCompletion()` on your stream following `cuda::SparsePyrLKOpticalFlow::calc`.

In either case it might be worth testing with the default stream (cuda::Stream::Null()) or without streams (which should have the same effect) to see if you get constistent results accross threads. If not it may be cause by something else.

---

<div class="post-metadata">

**Author:** ![keivan\_moazami](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/keivan_moazami/32/5713_2.png) [@keivan\_moazami](https://forum.opencv.org/u/keivan_moazami)\
**Post date:** [July 27, 2022, 9:02am UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632/3 "2022-07-27T09:02:19Z")

</div>

Thank you for your response.  
I use waitForCompletion() after call calc() method and use separate stream in each thread.  
It could be a bug ?  
like this bug [CUDA GoodFeaturesToTrackDetector is not ThreadSafe ? · Issue #18051 · opencv/opencv · GitHub](https://github.com/opencv/opencv/issues/18051)  
here is my code run in separate threads.

```auto
cuda::GpuMat GpuFrame;
GpuFrame.upload(frame, mForwardOpticalFlowStream);
cuda::GpuMat GpuLastFrame;
GpuLastFrame.upload(mLastFrame, mForwardOpticalFlowStream);
		
cuda::GpuMat gOldFeaturePoints, gNewFeaturePoints, gStatus, gErrors;
trackerUtils::uploadVector(allFeaturePoints, gOldFeaturePoints, CV_32FC2, mForwardOpticalFlowStream);
mSparseLK->calc(GpuLastFrame, GpuFrame, gOldFeaturePoints, gNewFeaturePoints, gStatus, gErrors, mForwardOpticalFlowStream);

trackerUtils::downloadVector(gStatus, status, CV_8UC1, mForwardOpticalFlowStream);
trackerUtils::downloadVector(gErrors, errors, CV_32FC1, mForwardOpticalFlowStream);
trackerUtils::downloadVector(gNewFeaturePoints, newFeaturePoints, CV_32FC2, mForwardOpticalFlowStream);
mForwardOpticalFlowStream.waitForCompletion();

cuda::GpuMat GpuFrameBackward;
GpuFrameBackward.upload(frame, mBackwardOpticalFlowStream);
cuda::GpuMat GpuLastFrameBackward;
GpuLastFrameBackward.upload(mLastFrame, mBackwardOpticalFlowStream);
cuda::GpuMat gNewBackwardFeaturePoints, gBackwardStatus, gBackwardErrors;
mSparseLKBackward->calc(GpuFrameBackward, GpuLastFrameBackward, gNewFeaturePoints, gNewBackwardFeaturePoints, gBackwardStatus, gBackwardErrors, mBackwardOpticalFlowStream);

trackerUtils::downloadVector(gBackwardStatus, backwardStatus, CV_8UC1, mBackwardOpticalFlowStream);
trackerUtils::downloadVector(gBackwardErrors, backwardErrors, CV_32FC1, mBackwardOpticalFlowStream);
trackerUtils::downloadVector(gNewBackwardFeaturePoints, newBackwardFeaturePoints, CV_32FC2, mBackwardOpticalFlowStream);
mBackwardOpticalFlowStream.waitForCompletion();

```

---

<div class="post-metadata">

**Author:** ![cudawarped](https://avatars.discourse-cdn.com/v4/letter/c/9dc877/32.png) [@cudawarped](https://forum.opencv.org/u/cudawarped)\
**Post date:** [July 27, 2022, 9:33am UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632/4 "2022-07-27T09:33:45Z")

</div>

> [@keivan\_moazami](#):
>
> It could be a bug ?  
> like this bug [CUDA GoodFeaturesToTrackDetector is not ThreadSafe ? · Issue #18051 · opencv/opencv · GitHub](https://github.com/opencv/opencv/issues/18051)

That doesn’t look like a bug, the routine wasn’t thread safe (the algorithm was using global memory as I mentioned above) until the author submitted [this](https://github.com/opencv/opencv_contrib/pull/2868) PR.

Are `mSparseLK` and `mSparseLKBackward` created inside each thread?

I’ll try to take a look later.

---

<div class="post-metadata">

**Author:** ![keivan\_moazami](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/keivan_moazami/32/5713_2.png) [@keivan\_moazami](https://forum.opencv.org/u/keivan_moazami)\
**Post date:** [July 27, 2022, 9:36am UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632/5 "2022-07-27T09:36:29Z")

</div>

`mSparseLK` and `mSparseLKBackward` are both in one thread

---

<div class="post-metadata">

**Author:** ![cudawarped](https://avatars.discourse-cdn.com/v4/letter/c/9dc877/32.png) [@cudawarped](https://forum.opencv.org/u/cudawarped)\
**Post date:** [July 27, 2022, 9:38am UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632/6 "2022-07-27T09:38:28Z")

</div>

> [@keivan\_moazami](#):
>
> `mSparseLKBackward`

Do you create a seperate instance of them in each thread, or create one instance of each and pass those to each thread?

---

<div class="post-metadata">

**Author:** ![keivan\_moazami](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/keivan_moazami/32/5713_2.png) [@keivan\_moazami](https://forum.opencv.org/u/keivan_moazami)\
**Post date:** [July 27, 2022, 9:40am UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632/7 "2022-07-27T09:40:21Z")

</div>

> [@cudawarped](#):
>
> create a seperate instance of them in each thread

I create a separate instance of them in each thread

---

<div class="post-metadata">

**Author:** ![cudawarped](https://avatars.discourse-cdn.com/v4/letter/c/9dc877/32.png) [@cudawarped](https://forum.opencv.org/u/cudawarped)\
**Post date:** [July 27, 2022, 12:13pm UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632/8 "2022-07-27T12:13:24Z")

</div>

> [@keivan\_moazami](#):
>
> I use waitForCompletion() after call calc() method and use separate stream in each thread.  
> It could be a bug ?  
> like this bug [CUDA GoodFeaturesToTrackDetector is not ThreadSafe ? · Issue #18051 · opencv/opencv · GitHub](https://github.com/opencv/opencv/issues/18051)

Just checked `SparsePyrLKOpticalFlow` is definitely not thread safe. It use constant and texture memory which are both globally defined

> <https://github.com/opencv/opencv_contrib/blob/9d0a451bee4cdaf9d3f76912e5abac6000865f1a/modules/cudaoptflow/src/cuda/pyrlk.cu#L61>

There appear to be versions which don’t use texture memory for both `short` and `int` types,

> <https://github.com/opencv/opencv_contrib/blob/9d0a451bee4cdaf9d3f76912e5abac6000865f1a/modules/cudaoptflow/src/cuda/pyrlk.cu#L774>

so I would guess but cannot confirm that these should be thread safe as long as you use the same window size and number of iterations per thread.

So in conclusion you could try `short` or `int` if applicable, re-write the routine to avoid textures or maybe use texture objects, use cuda::Stream::Null() which will hurt performance of maybe see how slow Nvidia’s hardware accelerated [dense optical flow](https://docs.opencv.org/4.x/db/d70/classcv_1_1cuda_1_1NvidiaOpticalFlow __2__ 0.html#details) is for your problem.

---

<div class="post-metadata">

**Author:** ![keivan\_moazami](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/keivan_moazami/32/5713_2.png) [@keivan\_moazami](https://forum.opencv.org/u/keivan_moazami)\
**Post date:** [July 29, 2022, 2:29pm UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632/9 "2022-07-29T14:29:25Z")

</div>

I use same win size & iteration in all threads.  
what is `short` and `int` types ? pixel data type ?

---

<div class="post-metadata">

**Author:** ![cudawarped](https://avatars.discourse-cdn.com/v4/letter/c/9dc877/32.png) [@cudawarped](https://forum.opencv.org/u/cudawarped)\
**Post date:** [July 29, 2022, 2:33pm UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632/10 "2022-07-29T14:33:02Z")

</div>

> [@keivan\_moazami](#):
>
> what is `short` and `int` types ? pixel data type

Yes pixel data type.

I would start by confirming that using the default stream `cv::cuda::Stream::Null()` gives you the same result in each thread. If so see if the execution time of that is acceptable. If not then try different data types.

---

<div class="post-metadata">

**Author:** ![keivan\_moazami](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/keivan_moazami/32/5713_2.png) [@keivan\_moazami](https://forum.opencv.org/u/keivan_moazami)\
**Post date:** [July 30, 2022, 11:50am UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632/11 "2022-07-30T11:50:18Z")

</div>

(post deleted by author)

---

<div class="post-metadata">

**Author:** ![keivan\_moazami](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/keivan_moazami/32/5713_2.png) [@keivan\_moazami](https://forum.opencv.org/u/keivan_moazami)\
**Post date:** [July 30, 2022, 11:51am UTC](https://forum.opencv.org/t/how-to-use-cuda-sparsepyrlkopticalflow-in-multi-thread-environment/9632/12 "2022-07-30T11:51:30Z")

</div>

Yes problem resolved by convert pixel format from `CV_8U` to `CV_16U`  
`frame.convertTo(shortFrame, CV_16U);`
