简体   繁体   English

uchar类型的Eigen :: Matrix和cv :: Mat之间的转换

[英]Conversion between Eigen::Matrix and cv::Mat of type uchar

I am testing Eigen <--> OpenCV using opencv2/core/eigen.hpp . 我正在使用opencv2/core/eigen.hpp测试Eigen <-> OpenCV。 The documentation seems to be lacking. 似乎缺少文档。

I could convert cv::Mat to Matrix. 我可以将cv :: Mat转换为Matrix。

Matrix<float,Dynamic, Dynamic> im;
cv::cv2eigen(cv::imread("lena.jpg", cv::IMREAD_GRAYSCALE),  im );

After this step, I do some processing in floats. 完成此步骤后,我将在浮点数中进行一些处理。 When I convert im back to cv::Mat and display the image I see a white image. 当我将im转换回cv::Mat并显示图像时,我看到了白色图像。

cv::Mat dst;
cv::eigen2cv(im,dst);

cv::imshow( "win", dst );
cv::waitKey(0);

I think the trouble is with dst still being a CV_32F Mat. 我认为麻烦是dst仍然是CV_32F Mat。 How can I get around this problem. 我该如何解决这个问题。

If the image type is CV_32F and you only see a white image then this suggests that the values of the image are not in the range [0, 1] . 如果图像类型为CV_32F并且您仅看到白色图像,则表明该图像的值不在[0, 1]范围内。

#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>

#include <Eigen/Core>
#include <opencv2/core/eigen.hpp>

#include <algorithm>
#include <iostream>

// ...

Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> im;

#if 0
// Wrong value range; you'll see only a white image.
cv::cv2eigen( cv::imread( "lena.jpg", cv::IMREAD_GRAYSCALE ),  im );
#else
// This should work ok.
cv::Mat image;

cv::Mat1b image1b = cv::imread( "lena.jpg", cv::IMREAD_GRAYSCALE );
image1b.convertTo( image, CV_32F, 1./255. );
cv::cv2eigen( image, im );
#endif

// Your processing
// ...

cv::Mat1f dst;
cv::eigen2cv( im, dst );

// Check the value range.
float maxV = *( std::max_element( dst.begin(), dst.end() ) );
float minV = *( std::min_element( dst.begin(), dst.end() ) );
std::cout << "value range = [" << minV << ", " << maxV << "]" << std::endl;

cv::imshow( "dst", dst );
cv::waitKey( 0 );

This is the output of the first variant ( #if 1 ): 这是第一个变量( #if 1 )的输出:

$ ./a.out 
value range = [24, 247]

And this is the output of the second variant ( #if 0 ): 这是第二个变量( #if 0 )的输出:

$ ./a.out
value range = [0.0941177, 0.968628]

After trying a little bit, realized that if all I need is rounding I can use convertTo() 尝试了一点之后,意识到如果我需要的是四舍五入,我可以使用convertTo()

cv::Mat dst,dst2;
cv::eigen2cv(im_inv,dst2);

dst2.convertTo(dst, CV_8UC1 );

cv::imshow( "win", dst );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM