5

I am using OpenCV 2.4.8 on VS2013. I have the following snippet of code:

    Mat img_sum = Mat::zeros(img_gray.size(), CV_32F);
    char file_name[FILENAME_MAX];
    for (int i = 0; i < SCALE_SIZE; i++){
        for (int j = 0; j < ORIENTATION_SIZE; j++){
            Mat srcImg;
            g_gabor[i*ORIENTATION_SIZE + j].conv_img(img_gray, srcImg, CV_GABOR_REAL);

            memset(file_name, NULL, FILENAME_MAX);
            sprintf_s(file_name, "gabor_images/%d_%d.png", i, j);
            imwrite(file_name, srcImg);
            imshow("Gabor滤波结果", srcImg);    //此时srcImg.type() == 1
            waitKey(100);
        }
    }
    imwrite("img_sum.png", img_sum);

The key issue is result of imwrite and imshow. They gave me different result.

The imshow image: imshow image

And, the imwrite image: imwrite image

I was wonderring if the reason is the image type. If so, how to convert image type to solve the problem.

Frank
  • 53
  • 6
  • imshow will render an image that can be displayed by your monitor. typically that is a 24 bit RGB image. On image writing to disk, typically 8 bit channel information is used, too. So if you have a 32 bit float matrix, opencv has to decide on how to render or save it. From documentation you'll see that for rendering, <= 0 will be rendered as black and >= 1 will be rendered as white, while for disk saving with imwrite, no scaling will apply so you'll have to scale manually before calling imwrite. – Micka Aug 03 '16 at 08:45

3 Answers3

7

With type CV_32F, you have to multiply your image by 255 before using imwrite.

Try imwrite(file_name, 255 *srcImg);.

Sunreef
  • 4,452
  • 21
  • 33
  • Thanks for your answer! My Image Type here is equal to 1, not CV_32F. Does it still works? – Frank Aug 03 '16 at 08:46
  • @Frank Can you show how you define your `img_gray` ? It seems strange that your `srcImg` should be of type `CV_8S` – Sunreef Aug 03 '16 at 09:04
  • You are right. Now I solve my problem by function convertTo(dst, type, scale, shift). – Frank Aug 03 '16 at 09:09
1

When you convert to CV_8U first, for instance with convertTo(dst, type, scale, shift), you can be sure both are identical.

SpamBot
  • 1,438
  • 11
  • 28
0

Now I solve my question by OpenCV function convertTo. It is not only a problem of the TYPE, scale and shift are needed, too.

        double minVal, maxVal;
        minMaxLoc(srcImg, &minVal, &maxVal); //find minimum and maximum intensities
        Mat charImage;
        srcImg.convertTo(charImage, CV_8U, 255.0 / (maxVal - minVal), -minVal);
        imwrite(file_name, charImage);
        imshow("Gabor滤波结果", srcImg);    //此时srcImg.type() == 1
Frank
  • 53
  • 6