使用 OpenCV 在图像上生成光流

Generate Opticalflow on images using OpenCV

我正在尝试 运行 OpenCV broxopticalflow 函数。 这是我的代码

int main(int argc, const char* argv[]){

        //use GPU 0
        setDevice(0);

        //source and target dirs
        string sourceDir = "source";
        string targetDir = "output";

        vector<string> filesInDir=getFileNamesFromDirAsVector(sourceDir.c_str());

        Ptr<BroxOpticalFlow> ptr = cv::cuda::BroxOpticalFlow::create(0.197f, 50.0f, 0.8f, 5, 150, 10);//(alpha ,gamma ,scale ,inner_iterations ,outer_iterations ,solver_iterations);   

        cout<<"Calculate flow for dir "<<sourceDir.c_str()<<endl;
        for (vector<string>::size_type i = 0; i <(filesInDir.size()-1); ++i){



            string frame0Name=sourceDir+"/"+filesInDir[i] ;
            string frame1Name=sourceDir+"/"+filesInDir[i+1];
            Mat frame0Color = imread(frame0Name,0);
            Mat frame1Color = imread(frame1Name,0);



            //frame0Color.convertTo(frame0Color, CV_32FC1, 1.0 / 255.0);
            //frame1Color.convertTo(frame1Color, CV_32FC1, 1.0 / 255.0);

            Mat frame0Gray, frame1Gray;
            //cv::cvtColor(frame0Color, frame0Gray, cv::COLOR_BGR2GRAY);
            //cv::cvtColor(frame1Color, frame1Gray, cv::COLOR_BGR2GRAY);
            frame0Color.convertTo(frame0Gray,CV_32FC1, 1.0 / 255.0);
            frame1Color.convertTo(frame1Gray,CV_32FC1, 1.0 / 255.0);
            cuda::GpuMat d_frame0;
            cuda::GpuMat d_frame1;
            d_frame0.download(frame0Gray);
            d_frame1.download(frame1Gray);
            cuda::GpuMat d_fu;
            ptr->calc(d_frame0, d_frame1, d_fu);
}

}

大部分代码是从 github 复制的。当我 运行 这段代码时,我 运行 进入以下错误:

OpenCV(4.1.0) /src/opencv_contrib-4.1.0/modules/cudaoptflow/src/brox.cpp:132: error: (-215:Assertion failed) frame0.type() == CV_32FC1 in function 'calc'

calc 函数检查第一个参数是否为 CV_32FC1 类型。这是代码失败的地方。基本上我的问题是如何将 gpu_mat 转换为所需的类型。我尝试了不同的方法,因为您可以在代码中看到注释行。如何将矩阵类型转换为 CV_32FC1?为什么我在代码中使用的转换不起作用,尽管它适用于 github?

上的大量实现

我对 gpumat 功能的下载和上传感到困惑。

    d_frame0.upload(frame0Gray);
    d_frame1.upload(frame1Gray);

上述更改修复了错误。