0

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.

serpentor
  • 25
  • 10

1 Answers1

2

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 );
berak
  • 39,159
  • 9
  • 91
  • 89
  • 1
    BTW using `at()` to sequnetially scan a big Mat is not ideal as it is quite slow - see http://stackoverflow.com/questions/25221421/c-opencv-fast-pixel-iteration/25224916#25224916 and http://docs.opencv.org/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#the-efficient-way. – Bull Sep 01 '14 at 14:37
  • the measurement was done in debug mode (where `.at` checks for image boundaries etc). In Release mode I didn't notice much impact using `.at` in my own measurements. So for uncritical tasks which don't have to be perfectly optimized, using `.at` isn't that bad and coding time can be used to optimize more important stuff. – Micka Sep 01 '14 at 15:38