0

I'm trying to create a blank image (later to be filled) using OpenCV, but it has to be in the same size with the predefined image as a new image. I tried the following code:

(image would be the picture of lena which is successfully displayed)

    Mat lena1(Size(image.cols,image.rows),CV_8UC1);
    namedWindow( "Display Image", CV_WINDOW_AUTOSIZE );
    //imshow( "Display Image", image );
    imshow("blank", lena1);

But for some reason, it still shows "image" and not lena1 (that would be the blank image with the same sizes of the predefined image).

Thank you!

2
  • You create the blank picture correctly, but I don't see any code to actually populate your matrix with lena1 pixels, so of course imshow displays blank picture.
    – pptaszni
    Commented Jan 15, 2020 at 11:44
  • This lena1(Size(image.cols,image.rows),CV_8UC1); is not correct way to create blank image. It initializes image with random values or perhaps we should say it leaves image as uninitialized, you should use overload taking Scalar with all components set to 0: lena1(Size(image.cols,image.rows),CV_8UC1,cv::Scalar());
    – rafix07
    Commented Jan 15, 2020 at 11:48

2 Answers 2

11

To create a blank image(image filled with zeros) use cv::Mat::zeros(). It will create a matrix with the dimension and type of your choice that is filled with zeros.

In your case, use the following code,

Mat lena1 = Mat::zeros(Size(image.cols,image.rows),CV_8UC1);

To fill that with a pre-loaded image,

image.copyTo(lena1);
1
  • Thanks! It was exactly that, thanks a lot, fully solved! Commented Jan 15, 2020 at 19:19
1

If you want to create an image with a single color you can do that too

Mat blueImage(cols, rows, CV_8UC1, Scalar(0, 0, 255));
1
  • 3
    I think it should be CV_8UC3 and not CV_8UC1 and this code will produce a red image. Blue image code: Mat blueImage(cols, rows, CV_8UC3, Scalar(255, 0, 0)); Commented May 31, 2022 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.