opencv光流算法多线程实现未加速

时间:2019-03-28 13:19:10

标签: c++ multithreading opencv opticalflow

我正在使用opencv光流算法建立一个实时视频拼接项目。我面临的问题是光流计算需要大量时间,我试图在多个线程中使用它我的代码是否有错误,或者是否有任何可替代opencv提供的光流算法?在此先感谢。 这是我的测试代码:

Ptr<cuda::DensePyrLKOpticalFlow> brox[6];


void callOptical(GpuMat d_frame0f, GpuMat d_frame1f, GpuMat d_flow, Stream stream,int i)
{
    brox[i]->calc(d_frame0f, d_frame1f, d_flow, stream);
    brox[i]->calc(d_frame1f, d_frame0f, d_flow, stream);
}


int main()
{
    String filename[12] = { "l0.png", "r0.png", "l1.png", "r1.png", "l2.png", "r2.png", "l3.png", "r3.png", "l4.png", "r4.png", "l5.png", "r5.png" };
    Mat frame[12];
    GpuMat d_frame[12];
    GpuMat d_framef[12];
    for (int i = 0; i < 6; i++)
    {
        frame[2 * i] = imread(filename[2 * i], IMREAD_GRAYSCALE);
        frame[2 * i + 1] = imread(filename[2 * i + 1], IMREAD_GRAYSCALE);
        d_frame[2 * i].upload(frame[2 * i]);
        d_frame[2 * i + 1].upload(frame[2 * i + 1]);
        brox[i] = cuda::DensePyrLKOpticalFlow::create(Size(7, 7));
    }
    GpuMat d_flow[6];
    GpuMat pre_flow[6];
    Stream stream[6];


    vector<std::thread> threads;

    const int64 start = getTickCount();

    for (int i = 0; i < 6; i++)
    {
        threads.emplace_back(
            callOptical,
            d_frame[2 * i],
            d_frame[2 * i + 1],
            d_flow[i],
            stream[i],
            i
            );
    }

    for (std::thread& t : threads)
        t.join();

    const double timeSec = (getTickCount() - start) / getTickFrequency();
    cout << "Brox : " << timeSec << " sec" << endl;
    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:0)

您的代码不是并行的-t.join()!!!您需要调用t.detach()并等待所有线程没有停止。

编辑:测试顺序:

void callOptical(GpuMat d_frame0f, GpuMat d_frame1f, GpuMat d_flow, Stream stream,int i)
{
    std::cout << i << " begin..." <<  std::endl;
    brox[i]->calc(d_frame0f, d_frame1f, d_flow, stream);
    brox[i]->calc(d_frame1f, d_frame0f, d_flow, stream);
    std::cout << i << " end!" <<  std::endl;
}

编辑:使用openmp!

#pragma omp parallel for
for (int i = 0; i < 6; i++)
{
    callOptical(d_frame[2 * i], d_frame[2 * i + 1], d_flow[i], stream[i], i);
}