Gusisin
Gusisin

Reputation: 49

In C++ using opencv I have a uint array converting to a a grayscale image, only shows a gray screen no image

I wonder if anyone can help me with this. I have an array (single dim) that holds enough uint values to populate a screen 120x160 in size. I want to load the array into a mat and display it as a grayscale image. I am not seeing it can anyone help?? Thanks in advance.

myarray[39360];
//..
//Code populates values between 0 and 255 to the array
// I have printed the array and the values are all 0 to 255
//..
Mat img,img1;

// load the array into a mat
img(120,160,CV_8UC1,myarray);

// convert the mat to a grayscale image, 3 channel instead of the current 1
img.convertTo(img1,CV_8UC3);
namedWindow("test",WINDOW_AUTOSIZE);
imshow("test",img1);
waitKey(0);

// windows pops up but just shows a gray blank page about mid tone :-(

Upvotes: 3

Views: 1527

Answers (2)

unlut
unlut

Reputation: 3775

Not sure why are you using Mat with 3 channel (CV_8UC3 means 8 bytes per pixel, unsigned, 3 channels) if you want a grayscale image, here is a complete example of what are you trying to do:

#include "opencv2/highgui.hpp"
#include <vector>
#include <iostream>
#include <ctype.h>
#include <cstdlib>

int main()
{
    //  create a uint8_t array, can be unsigned char too
    uint8_t myArray[120*160];

    //  fill values
    srand(time(0));
    for (int i = 0; i < 120*160; ++i)
    {
        myArray[i] = (rand() % 255) + 1;
    }

    //  create grayscale image
    cv::Mat imgGray(120, 160, CV_8UC1, myArray);

    cv::namedWindow("test", cv::WINDOW_AUTOSIZE);
    cv::imshow("test", imgGray);
    cv::waitKey(0);

    return 0;
}

Example output image: enter image description here

Upvotes: 2

Demosthenes
Demosthenes

Reputation: 1535

  • What type is myarray? I'm assuming unsigned char[].
  • If you display img, does it show correctly? By that, you can check if anything went wrong before the conversion.
  • The conversion to BGR (which is what you're doing, your converting grayscale to color with all colors the same) doesn't work that way. Here are two choices you have:

    cv::cvtColor(img,img1,cv::COLOR_GRAY2BGR);

    which does the same thing (possibly, in older versions, something like CV_GRAY2BGR), or create an array containing three times img and use cv::merge.

    • Finally, consider NOT converting to BGR at all. If you want a grayscale image, why isn't the 1-channel image sufficient? If you'd save it using cv::imwrite, it would even use less space...

Upvotes: 0

Related Questions