OpenCV显示双通道图像(光流)

时间:2011-10-07 22:46:37

标签: image-processing opencv

我的光流存储在2通道32F矩阵中。我想要想象内容,最简单的方法是什么?

如何将CV_32FC2转换为带有空蓝色通道的RGB,imshow可以处理?我正在使用OpenCV 2 C ++ API。

超级奖励积分

理想情况下,我会得到色调的流动角度和亮度的大小(饱和度恒定为100%)。

2 个答案:

答案 0 :(得分:20)

imshow只能处理1通道灰度和3-4通道BRG / BGRA图像。所以你需要自己做一个转换。

我认为你可以做类似的事情:

//extraxt x and y channels
cv::Mat xy[2]; //X,Y
cv::split(flow, xy);

//calculate angle and magnitude
cv::Mat magnitude, angle;
cv::cartToPolar(xy[0], xy[1], magnitude, angle, true);

//translate magnitude to range [0;1]
double mag_max;
cv::minMaxLoc(magnitude, 0, &mag_max);
magnitude.convertTo(magnitude, -1, 1.0 / mag_max);

//build hsv image
cv::Mat _hsv[3], hsv;
_hsv[0] = angle;
_hsv[1] = cv::Mat::ones(angle.size(), CV_32F);
_hsv[2] = magnitude;
cv::merge(_hsv, 3, hsv);

//convert to BGR and show
cv::Mat bgr;//CV_32FC3 matrix
cv::cvtColor(hsv, bgr, cv::COLOR_HSV2BGR);
cv::imshow("optical flow", bgr);

cv::waitKey(0);

答案 1 :(得分:5)

MPI Sintel Dataset提供了C和MatLab代码,用于可视化计算流程。从here下载训练集的地面实况光流。存档包含一个包含上述源代码的文件夹flow_code

您可以将代码移植到OpenCV,但是,我编写了一个简单的OpenCV包装器来轻松使用提供的代码。请注意,方法MotionToColor取自color_flow.cpp文件。请注意下面列表中的注释。

// Important to include this before flowIO.h!
#include "imageLib.h"
#include "flowIO.h"
#include "colorcode.h"
// I moved the MotionToColor method in a separate header file.
#include "motiontocolor.h"

cv::Mat flow;
// Compute optical flow (e.g. using OpenCV); result should be
// 2-channel float matrix.

assert(flow.channels() == 2);
// assert(flow.type() == CV_32F);

int rows = flow.rows;
int cols = flow.cols;

CFloatImage cFlow(cols, rows, 2);

// Convert flow to CFLoatImage:
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);

cv::Mat image(rows, cols, CV_8UC3, cv::Scalar(0, 0, 0));

// Compute back to cv::Mat with 3 channels in BGR:
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);
    }
}

// Display or output the image ...

以下是使用光流程代码和Ce Liu提供的示例图像时的结果。

Example images provided by Ce Liu.

Optical flow computed using the implementation provided by Ce Liu.