14

I'm relatively new to OpenCV and i've stumpled upon a problem. I've got an input image and want to convert it from Type CV_8U to CV_32F.

With some images it works just fine via input.convertTo(output, CV_32F) but with other images output would only give an completly white image.

Number of channels, dims is equal as well as depth. What is the problem?

moatilliatta
  • 365
  • 1
  • 7
  • 18
  • I don't really know how to troubleshoot this with the information given and I used OpenCV too long ago to have in-memory knowledge of these types of errors, but from the documentation: `The method converts source pixel values to the target datatype. saturate_cast<> is applied in the end to avoid possible overflows`. Is there something about the images that are failing that is causing saturate_cast<> to go nuts? – im so confused Oct 11 '12 at 14:47
  • Can you post an image where it does fail plus the code you are using? – Sassa Oct 11 '12 at 16:13

1 Answers1

20

I believe the result is normal.

When you use convertTo from CV_8U1 to CV32F1, a pixel value, for example, 255 becomes 255.0. But when you try `imshow' the resulting image, the command expects all pixel values to be between 0.0 and 1.0. that's why, without rescaling the image, the image will look all white.

So this will do the trick as zzz pointed out (thanks).

input.convertTo(output, CV_32F, 1.0/255.0)
Tae-Sung Shin
  • 20,215
  • 33
  • 138
  • 240
  • 2
    Therefore, use the third argument of convertTo as a scalefactor. In your case it would be 1.0/255.0. That way your image gets scaled as it converts. See the documentation at: http://docs.opencv.org/modules/core/doc/basic_structures.html?highlight=convertto#void%20Mat::convertTo%28OutputArray%20m,%20int%20rtype,%20double%20alpha,%20double%20beta%29%20const – zzzz Oct 12 '12 at 12:33
  • after doing this, my whole image is black now. Every pixel has very low value but looks like the range has not been changed still. – arvind.mohan Aug 30 '16 at 11:01
  • @arvind.mohan Please try to examine another reason it makes your image black. For example, Is your original image 16 bit? Are you passing an integer instead of float or double for scalingfactor? This method has been working for so long time and may not be the reason your converted image is black. – Tae-Sung Shin Aug 30 '16 at 14:52
  • @Tae-SungShin there is no difference in absolute values, the original image was 8bit int. I converted that to 64FC3 and scaled 1.0/255.0f. The scaling doesn't seems to be changing when I dumped the converted matrix as jpg image. – arvind.mohan Aug 31 '16 at 09:26
  • @arvind.mohan Wait, you are saving double-precision image to jpg? (1) you may not save double-precision image with OpenCV. (2) There are not many programs that can display double-precision image even if you could save the image. – Tae-Sung Shin Sep 01 '16 at 00:56