OpenCV cv::Mat displays empty gray images? Cant find the reason
I just want to display this "img1.jpg" image in a c++ project with using opencv libs for future processes, but it only displays an empty g开发者_运维技巧ray window. What is the reason of this. Is there a mistake in this code? please help!
Here is the code;
Mat img1;
char imagePath[256] = "img1.jpg";
img1 = imread(imagePath, CV_LOAD_IMAGE_GRAYSCALE);
namedWindow("result", 1);
imshow("result", img1);
Thanks...
I had the same problem and solved putting waitKey(1);
after imshow()
. The OpenCV documentation explains why:
This function is the only method in HighGUI that can fetch and handle events, so it needs to be called periodically for normal event processing, unless HighGUI is used within some environment that takes care of event processing.
Thanks @b_froz. For more detials about this issue,you can refer to: http://docs.opencv.org/2.4/modules/highgui/doc/user_interface.html#imshow
Note This function should be followed by waitKey function which displays the image for specified milliseconds. Otherwise, it won’t display the image. For example, waitKey(0) will display the window infinitely until any keypress (it is suitable for image display). waitKey(25) will display a frame for 25 ms, after which display will be automatically closed. (If you put it in a loop to read videos, it will display the video frame-by-frame)
So,not only waitkey(1)
could be put after imshow()
,but also waitkey(0)
or waitkey(other integers)
.Here is the explanation of the function waitkey()
: http://docs.opencv.org/2.4/modules/highgui/doc/user_interface.html#waitkey
Are you importing the correct library ? This is other very easy way to load one image:
#define CV_NO_BACKWARD_COMPATIBILITY
#include <cv.h>
#include <highgui.h>
#include <math.h>
main(){
IplImage* img = cvLoadImage("yourPicture.jpg");
cvNamedWindow("Original", 1);
cvShowImage("Original", img);
}
I think you have openCV correctly installed, so yo can type this (Ubuntu): g++ NameOfYourProgram.cpp -o Sample -I/usr/local/include/opencv/ -L/usr/local/lib -lcv -lhighgui ./sample
The problem you are having is due to the type of your Mat img1
. When you load your image with the flag CV_LOAD_IMAGE_GRAYSCALE
, the type of your Mat
is 0 (CV_8UC1
), and the function imshow()
is not able to show the image correctly.
You can solve this, converting your Mat
to type 16 (CV_8UC3
):
img1.convertTo(img1,CV_8UC3);
and then show it with imshow()
:
imshow("result", img1);
I hope this help.
精彩评论