LeOpArD
LeOpArD

Reputation: 498

How to work with 16 bit grayscale in OpenCV?

I can't find the answers to the these questions:

  1. Can I use OpenCV to display 16-bit grayscale pictures? I tried imshow() but nothing appeared on the windows created by OpenCV.

  2. How can I convert a 16-bit grayscale picture to a B5G6R5 picture? What parameter should I create cv::Mat with in order to store this structure? I tried cv::cvtColor(m_cvTmp, tmp, CV_GRAY2BGR565) but this function kept crashing. The documentation on miscellaneous image transformations does not tell the answer.

PS: the image I want to process is already in the memory.

Upvotes: 7

Views: 27505

Answers (2)

SSteve
SSteve

Reputation: 10728

According to the documentation for imshow, it will automatically scale a 16-bit grayscale to 8-bit in order to display it on the screen. I tested this with the following program:

#include <iostream>

#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace std;

int main(int argc, char *argv[]) {
    cv::Mat image;
    image = cv::imread("pic2.jpg");

    if (!image.data) {
        std::cout << "Image file not found\n";
        return 1;
    }

    cv::cvtColor(image, image, CV_BGR2GRAY);
    cv::Mat pic16bit;
    image.convertTo(pic16bit, CV_16U, 255); //convert to 16-bit by multiplying all values by 255

    // create image window named "asdfasdf"
    cv::namedWindow("asdfasdf");
    // show the image on window
    cv::imshow("asdfasdf", pic16bit);
    // wait for key
    cv::waitKey(0);

    return 0;
}

It displayed the grayscale image as expected. So if you are just getting a blank window, my guess is that your conversion from the other library to cv::Mat is not working correctly. For example, when I first tried to convert from 8-bit to 16-bit I got an-all black image because I forgot to multiply all the 8-bit values by 255.

As a first step in debugging I would try displaying some or all of the values in your 16-bit grayscale cv::Mat.

Also, as a general rule Stack Overflow works best if you only have a single question in your question. When there are multiple questions you will wind up with more than one valid answer but you can only accept one of them.

Upvotes: 1

Luca Davanzo
Luca Davanzo

Reputation: 21520

1) You have to take a look at this documentation.

Your code will be like:

Mat imageGrey = imread("<image_name>", CV_LOAD_IMAGE_GRAYSCALE);

2)

Mat imageGrey = imread("<image_name>", CV_LOAD_IMAGE_GRAYSCALE);
Mat imageBGR;
cvtColor(imageGrey, imageBGR, CV_GRAY2BGR565);

Does it works?

Upvotes: 0

Related Questions