从 SO 答案之一,使用光流进行分割需要密集的光流。我修改了这段代码。它使用calcOpticalFlowFarneback函数来计算两个连续帧之间的密集流场。
sqrt(位移_in_x^2 + 位移_in_y^2)
该函数将位移返回为 CV_32FC2
这是我的代码:-
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include <iostream>
using namespace cv;
using namespace std;
void drawOptFlowMap(const Mat& flow, Mat& cflowmap, int step,
double scale, const Scalar& color)
{
for(int y = 0; y < cflowmap.rows; y += step)
for(int x = 0; x < cflowmap.cols; x += step)
{
const Point2f& fxy = flow.at<Point2f>(y, x);
line(cflowmap, Point(x,y), Point(cvRound(x+fxy.x), cvRound(y+fxy.y)),
color);
circle(cflowmap, Point(x,y), 2, color, -1);
}
}
int main()
{
VideoCapture cap("vip.avi");
if( !cap.isOpened() )
return -1;
Mat prevgray, gray, flow, cflow, frame;
double col = cap.get(CV_CAP_PROP_FRAME_WIDTH);
double row = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
Mat flow_img = Mat::zeros(row,col,CV_8UC1);
namedWindow("flow", 1);
namedWindow("segmented",1);
for(;;)
{
cap >> frame;
cvtColor(frame, gray, CV_BGR2GRAY);
if( prevgray.data )
{
calcOpticalFlowFarneback(prevgray, gray, flow, 0.5, 3, 15, 15, 5, 1.2, 0);
cvtColor(prevgray, cflow, CV_GRAY2BGR);
drawOptFlowMap(flow, cflow, 8, 1.5, CV_RGB(0, 255, 0));
imshow("flow", cflow);
}
//This part I added to compute Magnitude of flow
for(int i=0;i<gray.rows;i++)
for(int j=0;j<gray.cols;j++)
flow_img.at<uchar>(i,j)= cvRound( sqrt ( pow (flow.at<Vec2f>(i,j)[0] ,2 )+ pow ( flow.at<Vec2f>(i,j)[1],2) ));
//threshold image
threshold(flow_img,flow_img,10,255,THRESH_BINARY); //some arbitrary thresh value 10
imshow("segmented",flow_img);
if(waitKey(30)>=0)
break;
std::swap(prevgray, gray);
}
return 0;
}
我正在使用 Microsoft Visual C++ 2010 并且没有构建错误。但程序不会运行并抛出以下内容:
在控制台窗口中,我得到:
我不明白我在哪里犯了错误。谁能帮帮我。这里有类似的 SO 问题,答案是我使用的代码。我仍然遇到上述问题