mkuse
mkuse

Reputation: 2488

Conversion between Eigen::Matrix and cv::Mat of type uchar

I am testing Eigen <--> OpenCV using opencv2/core/eigen.hpp. The documentation seems to be lacking.

I could convert cv::Mat to 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.

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. How can I get around this problem.

Upvotes: 1

Views: 3814

Answers (2)

mkuse
mkuse

Reputation: 2488

After trying a little bit, realized that if all I need is rounding I can use convertTo()

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

dst2.convertTo(dst, CV_8UC1 );

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

Upvotes: 0

nils
nils

Reputation: 2524

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].

#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):

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

And this is the output of the second variant (#if 0):

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

Upvotes: 2

Related Questions