2
votes

When I run the provided code, a imshow() opens a window but it is just an empty gray window. The code executes successfully (doesn't trigger the !image.data check.) The imwrite() function does successfully write the image to a file so I don't think it is a problem with reading the image.

I also tried opening a named window first, and then calling imshow to that window, but that also didn't help.

It seems like there are a few other people having this issue on this site. I browsed the answers and tried the solutions but nothing worked. Also I could not find anyone using opencv 4.0 with c++.

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <string>

using namespace std;
using namespace cv;

int main() {
    Mat image;
    image = imread("./887.jpg");
    if (!image.data)
    {
        cout << "Could not open or find the image" << std::endl;
        return -1;
    }

    imwrite("test.jpg", image);
    waitKey(1);
    imshow("Display window", image);                   // Show our image inside it.
    waitKey(0);


    return 0;
}

I expect the image to show up in a window titled "Display window", the window does show up but it is just an empty gray box.

2
If anyone with openCV4 installed with Visual Studio 2017 wants to try running this to see if it might be a bug associated with my computer rather than OpenCV that would be appreciated! - Patrick Leppink-Shands
Are you running your application from visual studio? - Elvis Oric
I wouldn't do !image.data. I think it is better to use empty !image.empty(). If you manage to save an image then it probably is ok.... You can always try to show an image created by you, like cv::Mat example(600, 800, CV_8UC3, cv::scalar(0,0,255)); which is a red image - api55
@api55, should be image.empty(), but it is the same check. - Elvis Oric
I am running the application from visual studio. I believe that it is successfully reading the image, because the imwrite function saves the correct image. - Patrick Leppink-Shands

2 Answers

0
votes

Specify absolute path to the image and check if it is working correctly.

If you are running your application from Visual Studio, you need to specify current working directory to be the same as location of the image.

You can also check with ifstream if file exists with

inputStream.open("887.jpg");
if (inputStream.fail()) {
    // bad file path
}

just to confirm that current working directory is properly set.

0
votes

Ok, sorry about this. The image I was trying to display is very large, and only visible part was the corner of image which is gray. Once I scaled down the image it appeared just fine. So sorry for wasting everyone's time.