Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalize pixel values between 0 and 1

I am looking to normalize the pixel values of an image to the range [0..1] using C++/OpenCV. However, when I do the normalization using either image *= 1./255 or the normalize function the pixel values are rounded down to zero. I have tried setting the image to type CV_32FC3.

Below is the code I have:

  Mat image;
  image = imread(imageLoc, CV_LOAD_IMAGE_COLOR | CV_LOAD_IMAGE_ANYDEPTH);

  Mat tempImage;

  // (didn't work) tempImage *= 1./255;

  image.convertTo(tempImage, CV_32F, 3);
  normalize(image, tempImage, 0, 1, CV_MINMAX);

  int r = 100;
  int c = 150;

  uchar* ptr = (uchar*)(tempImage.data + r * tempImage.step);
  Vec3f tempVals;
  tempVals.val[0] =  ptr[3*c+1];
  tempVals.val[1] =  ptr[3*c+2];
  tempVals.val[2] =  ptr[3*c+3];
  cout<<" temp image - "<< tempVals << endl;

  uchar* ptr2 = (uchar*)(image.data + r * image.step);
  Vec3f imVals;
  imVals.val[0] =  ptr2[3*c+1];
  imVals.val[1] =  ptr2[3*c+2];
  imVals.val[2] =  ptr2[3*c+3];
  cout<<" image - "<< imVals << endl;

This produces the following output in the console:

temp image - [0, 0, 0]
image - [90, 78, 60]
like image 282
tjp Avatar asked Jun 27 '13 14:06

tjp


2 Answers

You can make convertTo() do the normalization for you:

image.convertTo(tempImage, CV_32FC3, 1.f/255);

You are passing 3 to convertTo(), presumably as channel-count, but that's not the correct signature.

like image 185
Adi Shavit Avatar answered Oct 01 '22 15:10

Adi Shavit


I used the normalize function and it worked (Java):

Core.normalize(src,dst,0.0,1.0,Core.NORM_MINMAX,CvType.CV_32FC1);

You should use a 32F depth for your destination image. I believe the reason for this, is that since you need to get decimal values, you should use an a non-integer OpenCV data type. According to this table, the float types correspond to the 32F depth. I chose the number of channels to be 1 and it worked; CV_32FC1

Remember also that it's unlikely to spot any visual difference in the image. Finally, since you probably have thousands of pixels in your image, your console might seem that it's printing only zeros. However due to the large amount of data, try to use CTRL+F to see what's going on. Hope this helps.

like image 39
arxakoulini Avatar answered Oct 01 '22 14:10

arxakoulini