简体   繁体   中英

Read OpenCV Mat 16bit to QImage 8bit Greyscale

What i want to do

  1. File : TIFF, 2 Pages, Greyscale, 16bit
  2. OpenCV : 2x Mat, Greyscale, 16bit (CV_16UC1)
  3. Qt : 2x QImage, Greyscale, 8bit (Format_Greyscale8)

I want to read a 16bit Tiff and then convert it to show it as 8bit.

Reading

void ImgProc::Load_Image_2xTiff_16bit_G(Mat *Mat_A_in, Mat *Mat_B_in, string file_name)
{  
    vector<Mat> vec_Mat;
    vec_Mat.reserve(2);

    imreadmulti(file_name, vec_Mat);

    *Mat_A_in = vec_Mat[0];
    *Mat_B_in = vec_Mat[1];
}

Conversion

void ImgProc::Convert_Mat16_2_QIm8(QImage *QIm_Out, Mat *Mat_In, double scale_factor)
{
    unsigned int rows = Mat_In->rows;
    unsigned int cols = Mat_In->cols;
    *QIm_Out = QImage(cols, rows, QImage::Format_Grayscale8);
    unsigned char* line_QIm;

    if (!Mat_In->data)
        return;

    for(unsigned int y = 0; y < rows; y++)
    {
        line_QIm = QIm_Out->scanLine(y);
        for(unsigned int x = 0; x < cols; x++)
        {
            line_QIm[x] = (unsigned char)(Mat_In->at<ushort>(y, x) * scale_factor);
        }
    }
}

Problem

When i use Mat_In->at<ushort>(y, x) (read 16bits) it crashes with abort() has been called . Same happens if i use <short> instead.

When i use Mat_In->at<uchar>(y, x) (read 8bits) it works, but cuts off information without scaling. That shows up as "black holes" in the brighter areas of the image, probably an overflow effect.

I think i should mention, that the camera that took the images only uses 14bit depth.

I faced the same type kind of issue. The following code is the solution I used to fix that case.

   #include <opencv2/core.hpp>
   #include <opencv2/imgproc.hpp>
   #include <opencv2/highgui.hpp>

   #include <QImage>

    int main(void)
    {

      //Read the 16 bit per pixel image.
      cv::Mat I = cv::imread('16BitsPerPixelImage.tiff',cv::IMREAD_ANYDEPTH|cv::IMREAD_ANYCOLOR);

     //Convert from 16 bit per pixel to 8 bit per pixel using a min max normalization and store it a 8 bit per pixel.
     cv::normalize(I,I,0.,255.,cv::NORM_MINMAX,CV_8U);

    // Then actualy the easiest way to convert it to a QImage is to save a temporary file and open it using QT functions.
    // PNG use a compression without loss algorithm.
      cv::imwrite("/tmp/convert16to8.png",I);

      QImage QI;

      QI.load("/tmp/convert16to8.png");

      return EXIT_SUCCESS;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM