cv::Mat flowToColor(const cv::Mat & flow, float max) { assert(flow.channels() == 2); int rows = flow.rows; int cols = flow.cols; CFloatImage cFlow(cols, rows, 2); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cFlow.Pixel(j, i, 0) = flow.at<cv::Vec2f>(i, j)[0]; cFlow.Pixel(j, i, 1) = flow.at<cv::Vec2f>(i, j)[1]; } } CByteImage cImage; MotionToColor(cFlow, cImage, max); assert(cImage.Shape().height == rows); assert(cImage.Shape().width == cols); assert(cImage.Shape().nBands == 3); cv::Mat image(rows, cols, CV_8UC3, cv::Scalar(0, 0, 0)); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { image.at<cv::Vec3b>(i, j)[0] = cImage.Pixel(j, i, 0); image.at<cv::Vec3b>(i, j)[1] = cImage.Pixel(j, i, 1); image.at<cv::Vec3b>(i, j)[2] = cImage.Pixel(j, i, 2); } } return image; }
int main(int argc, char *argv[]) { try { int argn = 1; if (argc > 1 && argv[1][0]=='-' && argv[1][1]=='q') { verbose = 0; argn++; } if (argn >= argc-3 && argn <= argc-2) { char *flowname = argv[argn++]; char *outname = argv[argn++]; float maxmotion = argn < argc ? atof(argv[argn++]) : -1; CFloatImage im, fband; ReadFlowFile(im, flowname); CByteImage band, outim; CShape sh = im.Shape(); sh.nBands = 3; outim.ReAllocate(sh); outim.ClearPixels(); MotionToColor(im, outim, maxmotion); WriteImageVerb(outim, outname, verbose); } else throw CError(usage, argv[0]); } catch (CError &err) { fprintf(stderr, err.message); fprintf(stderr, "\n"); return -1; } return 0; }
void opticalFlow::runFlowEstimator(const char* i1file, const char* i2file, const char* seqName, spm_bp_params* params) { Mat in1 = imread(i1file); Mat in2 = imread(i2file); cv::GaussianBlur(in1,in1,cv::Size(0,0),0.9); cv::GaussianBlur(in2,in2,cv::Size(0,0),0.9); in1.copyTo(im1); in2.copyTo(im2); height1 = im1.rows; width1 = im1.cols; height2 = im2.rows; width2 = im2.cols; flow12.create(height1,width1); flow21.create(height2,width2); occMap.create(height1,width1); //optical flow from frame 1 to frame 2 opticalFlowEst( im1, im2, flow12, params); //optical flow from frame 2 to frame 1 opticalFlowEst( im2, im1, flow21, params); //left-right consistancy check (occlusion estimation) occMap.create(height1,width1); occMatpEst( flow12, flow21, occMap); //post processing (occlusion region filling) opticalFlowRefine(flow12, occMap, im1, flow_refined); //write result Mat_<Vec3b> flow_color_t; MotionToColor(flow_refined, flow_color_t, -1); cv::imshow("Flow aft Post-processing",flow_color_t); cv::imwrite("flow_visualization.png",flow_color_t); flow_color_t.release(); char flow_file_name[200]; sprintf(flow_file_name,"%s.flo",seqName); WriteFlowFile(flow_file_name,flow_refined,height1,width1); }