serpentor
serpentor

Reputation: 25

Trying to implement a tiny part of matlab code in C++ using opencv

I am trying to convert an image to double precision using opencv. I am trying to imitate the im2double function available in MATLAB in c++. So, for this what i did was..

 Mat IMG = imread("lena.bmp");
Size size(8,8);

Mat img,img_re,grey;
cvtColor( IMG, img, CV_BGR2GRAY );

resize(img,img_re,size);
img_re.convertTo( grey, CV_64FC3, 1.0/255.0 );
std::cout<<grey<<std::endl;

unsigned char *input = (unsigned char*)(grey.data);

 grey: [0.3764705882352941, 0.5176470588235293, 0.4352941176470588, 0.8274509803921568;
       0.392156862745098, 0.5254901960784314, 0.7372549019607844, 0.6431372549019607;
       0.4431372549019608, 0.6431372549019607, 0.7176470588235294, 0.5607843137254902;
       0.5333333333333333, 0.3254901960784314, 0.6862745098039216, 0.8431372549019608]

The data stored in grey is almost similar to the data obtained from matlab. the pixels have a range of [0,1]here. But ,my problem starts here. I want to now access the pixel values from 'grey' and save it to a boost matrix. So for this i use..

 for (unsigned i=0; i < height; ++i)
{
    for (unsigned j=0; j < width; ++j )
    {
        image(i,j) = input[grey.step * j + i ];
    }
}

  image:: [4,4]((24,24,144,144),(24,24,144,144),(24,216,144,224),(24,63,144,63))

After this step all the values in the matrix have a range of [0,255]. grey scale images are between [0,255] but why do it get the values between [0,1] in the first case.

Upvotes: 0

Views: 106

Answers (1)

berak
berak

Reputation: 39796

please stay away from accessing Mat's raw 'data' pointer, and use:

grey.at<double>(i,j);

instead.

also, if im_re is a 1 channel, grayscale image, your typeflag is wrong, should be:

img_re.convertTo( grey, CV_64F, 1.0/255.0 );

Upvotes: 2

Related Questions