imread not working in Opencv - c++

I'm trying to use the imread function from OpenCV2.2.
My code is very simple.
cv::Mat host= imread("1.bmp", CV_LOAD_IMAGE_GRAYSCALE);
After that, the host matrix became filled by zeros pointers, i.e. an image has not loaded.
If I use cvLoadImage then it all works properly.
The file exists, and I am not mixing the release and debug libraries. Why imread doesn't work?

Reproduced with opencv 2.4.8.
If you are running in Debug, check that you are also using debug libraries, it fixed our problem. : OpenCV imread(filename) fails in debug mode when using release libraries.

i was facing the same problem with 2.4.6 . The reason was that while selecting the library , i had selected both the debug version and the release version. When i selected only the debug version for the library everything worked fine

I can confirm, that there are some problems with imread in OpenCV 2.2. However the problems only occurred on a Windows 32bit system. On a linux and on a mac it worked. I can't tell why it didn't work, but we had a small workaround for that.
We fixed this problem with the following macros, maybe you could try this out and use "ourImread" from then on.
#ifdef WIN32
#define ourImread(filename, isColor) cvLoadImage(filename.c_str(), isColor)
#else
#define ourImread(filename, isColor) imread(filename, isColor)
#endif

I've had the same problem
cv::Mat image= cv::imread("immagine12.jpg"); // Read the file
if(! image.data ) // Check for invalid input
{
cout << "Could not open or find the image" << std::endl ;
cv::waitKey(5000);
return -1;
}
cv::namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image );
//non so perchè ma senza il waitKey e lasciando solo il system pause non carica l'immagine...
cv::waitKey(5000);
system("pause");
but I fixed it when I inserted the cv::waitKey(5000);
I don't know why but with system pause it can't load the image and it goes on pause after it loads the image!

I have similar problem on Linux, when reading 32 bit tiff images only.
Mat mat= imread(filename, CV_LOAD_IMAGE_ANYDEPTH);
Problem was because OpenCV was not build with Tiff support for some reason.

If you think that it is an OpenCV bug then, please, post your image and instructions for reproducing to the OpenCV bugtracker.

I know it is late but someone might found this helpful. I was facing the same problem while using imread using OpenCV-3.0. I tried all solutions but actually I was not adding the library opencv2/imgcodecs.hpp. Although imshow was working without it, but after I add this I was able to read the image.

Opencv4.3 Windows10 x64 Visual Studio 2019 I finally solved that problem!!!
Ok, now, when you meet the problem, you can try:
Check your settings, make sure you don't mix include .lib file in "Project->Properties->Linker->Input" for Release/Debug, that opencv_xxx430d.lib(note the d) is for Debug, and opencv_xxx430.lib(no d) is for Release, and the platform is x64.
And in C/C++->General, you need to set the Additional include directory that X:/(opencv_build/install)/include and X:/(opencv_build/install)/include/opencv2 respectively for Release/Debug.
Maybe you should #include <opencv2/imgcodecs.hpp>.
Finally, the Unicode Problem, which is also my problem that, the unicode symbol in the image file path, fuck! I don't know why because my code is very normal string path = "D:/kk.jpg(note that, it is / not \) but you can try to debug your code, maybe you can find there is something like path = "?D:/kk.jpg", what the fuck! So don't directly copy/paste your image path, even you've already use the absolute path, you can still meet the unicode problem, so, what you need to do is delete the line of code(string path = "D:/kk.jpg), and then just retype each character one by one! If you're lucky, you will see that image with imshow. Good luck.

see related question here
Please make sure your path is correct ,
According to the Opencv's API , I'd try this call:
arrayMat[i]=imread("1.jpg" , 1 );
The parameters for imread :
Mat imread(const string& filename, int flags=1)
Loads an image from a file.
Parameters:
filename – Name of file to be loaded.
flags – Specifies color type of the loaded image:
>0 the loaded image is forced to be a 3-channel color image
=0 the loaded image is forced to be grayscale
<0 the loaded image will be loaded as-is (note that in the current implementation the alpha channel, if any, is stripped from the output image, e.g. 4-channel RGBA image will be loaded as RGB if ).
Good luck
S

I have the same problem. I solved it. The key is whether the filename has jpg.
If the filename is p1, you should use something like this imread("p1.jpg"). But we often set the filename as p1.jpg, here we should use something like this imread("p1.jpg.jpg").

This also happened to me, my simple solution was to use the C API and then convert to Mat:
IplImage* img = cvLoadImage("c://frame_201.bmp");
Mat mat = Mat(img);

The reverse is also true: if you are building Release and you have Debug libraries, then imread() quietly fails (errno is 0 after imread(), but the image object is not populated).

Another possibility:
If you're on OS X and statically link OpenCV be sure to use libjpeg which is bundled with OpenCV, not the system's one.
I had similar problem with OpenCV 3.0, except that cvLoadImage was not working as well. So, this might not really answer your question, but maybe it will help someone else.

I also had the very same problem that imread didn't work and cvLoadImage did work.
I decided to create a new Visual Studio from scratch and now it works.
There is no general problem with imread in OpenCV 2.4.3 under win32.

I know you want use "imread" & "CV_LOAD_IMAGE_GRAYSCALE" and convert automatically.
But this other way for load one picture and convert to gray scale:
define CV_NO_BACKWARD_COMPATIBILITY
#include <cv.h>
#include <highgui.h>
#include <math.h>
int main(){
/* load the image */
IplImage* img = cvLoadImage("yourPicture.bmp"); //jpg - bmp
/* retrieve properties */
int width = img->width;
int height = img->height;
int nchannels = img->nChannels;
int step = img->widthStep;
IplImage* img2 = cvCreateImage(cvSize(img->height, img->width),IPL_DEPTH_8U,1);
/* setup the pointer to access image data */
uchar *data = ( uchar* )img->imageData;
uchar *data2= ( uchar* )img2->imageData;
/* convert to grayscale manually */
int i, j, r, g, b, byte;
for( i = 0 ; i < height ; i++ ) {
for( j = 0 ; j < width ; j++ ) {
r = data[i*step + j*nchannels + 0];
g = data[i*step + j*nchannels + 1];
b = data[i*step + j*nchannels + 2];
byte = ( r + g + b ) / 3;
int v0=0, v1=0, v2=0;
data2[i*(img2->widthStep)+j*(img2->nChannels)+0] = byte;
data2[i*(img2->widthStep)+j*(img2->nChannels)+1] = byte;
data2[i*(img2->widthStep)+j*(img2->nChannels)+2] = byte;
}
}
cvNamedWindow("ImagenColor", 1);
cvShowImage("ImagenColor", img);
cvNamedWindow("Gray", 1);
cvShowImage("Gray", img2);
}

Related

Unhandled exception Microsoft C++ exception: cv::Exception at memory location

I just started with OpenCV. I downloaded OpenCV 2.4.9, and installed MSVS 2010. My Windows is X64. I followed the following steps:
a. Under Configuration Properties, click Debugging -> Environment and copy paste: PATH=C:\opencv\build\x86\vc10\bin
b. VC++ Directories -> Include directories and add the entries: C:\opencv\build\include
c. VC++ Directories -> Library directories and add the entries: C:\opencv\build\x86\vc10\lib
d. Linker -> Input -> Additional Dependencies and add the following:
opencv_calib3d249.lib;opencv_contrib249.lib;opencv_core249.lib;opencv_features2d249.lib;opencv_flann249.lib;opencv_gpu249.lib;opencv_nonfree249.lib;opencv_highgui249.lib;opencv_imgproc249.lib;opencv_legacy249.lib;opencv_ml249.lib;opencv_objdetect249.lib;opencv_ts249.lib;opencv_video249.lib;
I ran the following code:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
int main() {
// read an image
cv::Mat image= cv::imread("img.jpg");
// create image window named "My Image"
cv::namedWindow("My Image");
cv::waitKey(1000);
// show the image on window
cv::imshow("My Image", image);
// wait key for 5000 ms
cv::waitKey(50);
return 1;
}
To get the error:
Unhandled exception at 0x76d2b727 in BTP1.exe: Microsoft C++ exception: cv::Exception at memory location 0x003af414
I figured this might be because of the X64 and x86 mismatch. On changing the entries in a. to PATH=C:\opencv\build\ x64 \vc10\bin and in c. to C:\opencv\build\ x64 \vc10\lib, I get the following error:
The application was unable to start correctly (0xc000007b). Click OK to close the application.
Any tips on how I can get over this issue?
This is probably happening because the image you are trying to display is empty, perhaps because the image isn't in the right folder. To confirm this, change your code to
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream> // std::cout
int main() {
// read an image
cv::Mat image= cv::imread("img.jpg");
// add the following lines
if(image.empty())
std::cout << "failed to open img.jpg" << std::endl;
else
std::cout << "img.jpg loaded OK" << std::endl;
... // the rest of your code
Resolved the problem. On some tinkering, I found that the program was running in the Release mode, and not the Debug mode.
It was a problem with the Additional Dependencies. Did not add the Debug versions of the same. (XYZ249d.lib)
To add to the other answers, this also commonly occurs if you pass a color image into a tool that requires a grayscale image (ie single channel).
You can convert it to grayscale using the following code:
cv::Mat img_gray;
cv::cvtColor(img_color, img_gray, cv::COLOR_BGR2GRAY);
You can extract and combine individual color channels using the following code:
cv::Mat img_bgr[3];
cv::split(img_color, img_bgr);
//Note: OpenCV uses BGR color order
//img_bgr[0] = blue channel
//img_bgr[1] = green channel
//img_bgr[2] = red channel
cv::Mat img_gray = img_bgr[2] - img_bgr[1]; //laser line extraction is typically red channel minus green channel
I had a similar problem, I just had to give the path of the image file
for example -
D:\image.png

OpenCV imwrite() not saving image

I am trying to save an image from OpenCV on my mac and I am using the following code and so far it has not been working.
cv::imwrite("/Users/nickporter/Desktop/Gray_Image.jpg", cvImage);
Can anyone see why this might not be saving?
OpenCV does have problems in saving to JPG images sometimes, try to save to BMP instead:
cv::imwrite("/Users/nickporter/Desktop/Gray_Image.bmp", cvImage);
Also, before this, make sure you image cvImage is valid. You can check it by showing the image first:
namedWindow("image", WINDOW_AUTOSIZE);
imshow("image", cvImage);
waitKey(30);
I met the same problem and one possible reason is that the target folder to place your image. Suppose you want copy A.jpg to folder "C:\\folder1\\folder2\\", but in fact when folder2 doesn't exist, the copy cannot be successful(It is from my actual test, not from official announcement). And I solved this issue by checking whether the folder exists and create one folder if it doesn't exist. Here is some code may it help using c++ & boost::filesystem. May it help.
#include <boost/filesystem.hpp>
#include <iostream>
std::string str_target="C:\\folder1\\folder2\\img.jpg";
boost::filesystem::path path_target(str_target);
boost::filesystem::path path_folder=path_target.parent_path();//extract folder
if(!boost::filesystem::exists(path_folder)) //create folder if it doesn't exist
{
boost::filesystem::create_directory(path_folder);
}
cv::imwrite(str_target,input_img);
I also suggest to check folder permissions. Opencv quietly returns from imwrite without any exception even if output folder doesn't have write permissions.
I've just had a similar problem, loading in a jpg and trying to save it back as a jpg. Added this code and it seem to be fine now.
vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
compression_params.push_back(100);
And you need to include the param in your writefile.
cv::imwrite("/Users/nickporter/Desktop/Gray_Image.jpg", cvImage, compression_params);
OpenCV 3.2 imwrite() seems to have a problem to write jpg file with Windows Debug mode. I use this way instead of imwrite().
cv::Mat cvImage;
#ifdef DEBUG
IplImage image = IplImage(cvImage);
cvSaveImage("filename.jpg", &image);
#else
cv::imwrite("filename.jpg", cvImage);
#endif
The following function can be dropped into your code to support writing out jpg images for debugging purposes.
You just need to pass in an image and a filename for it. In the function, specify a path you wish to write to & have permission to do so with.
void imageWrite(const cv::Mat &image, const std::string filename)
{
// Support for writing JPG
vector<int> compression_params;
compression_params.push_back( CV_IMWRITE_JPEG_QUALITY );
compression_params.push_back( 100 );
// This writes to the specified path
std::string path = "/path/you/provide/" + filename + ".jpg";
cv::imwrite(path, image, compression_params);
}
Although it is not true for your case. This problem may arise if the image path given as argument to the cv::imwrite function exceeds the allowed maximum path length (or possibly allowed file name length) for your system.
for linux see: https://unix.stackexchange.com/questions/32795/what-is-the-maximum-allowed-filename-and-folder-size-with-ecryptfs
for windows see: https://www.quora.com/What-is-the-maximum-character-limit-for-file-names-in-windows-10

How do I load an image (raw bytes) with OpenCV?

I am using Mat input = imread(filename); to read an image but I'd like to do it from memory instead. The source of the file is from an HTTP server. To make it faster, instead of writing the file to disk and then use imread() to read from it, i'd like to skip a step and directly load it from memory. How do I go about doing this?
Updated to add error
I tried the following but I'm getting segmentation fault
char * do_stuff(char img[])
{
vector<char> vec(img, img + strlen(img));
Mat input = imdecode(Mat(vec), 1);
}
See the man page for imdecode().
http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#imdecode
I had a similar problem. I needed to decode a jpeg image stream in memory and use the Mat image output for further analysis.
The documentation on OpenCV::imdecode did not provide me enough information to solve the problem.
However, the code here by OP worked for me. This is how I used it ( in C++ ):
//Here pImageData is [unsigned char *] that points to a jpeg compressed image buffer;
// ImageDataSize is the size of compressed content in buffer;
// The image here is grayscale;
cv::vector<unsigned char> ImVec(pImageData, pImageData + ImageDataSize);
cv:Mat ImMat;
ImMat = imdecode(ImVec, 1);
To check I saved the ImMat and was able to open the image file using a image viewer.
cv::imwrite("opencvDecodedImage.jpg", ImMat);
I used : OpenCV 2.4.10 binaries for VC10 on x86.
I hope this information can help others.

OpenCV Error: Null pointer (NULL array pointer is passed) in cvGetMat

I have run the code of Caltech-Lanes-Detection. There is my command:
$ ./LaneDetector32 --show --list-file=/home/me/caltech-lanes/cordova1/list.txt --list-path=/home/me/caltech-lanes/cordova1/ --output-suffix=_result
and there is a problem as following:
main.cc:187 msg Loaded camera file
main.cc:194 msg Loaded lanes config file
main.cc:249 msg Processing image: /home/me/caltech-lanes/cordova1/f00000.png
OpenCV Error: Null pointer (NULL array pointer is passed) in cvGetMat, file /home/me/OpenCV-2.0.0/src/cxcore/cxarray.cpp, line 2370
terminate called after throwing an instance of 'cv::Exception'
and if I run this command:
eog /home/me/caltech-lanes/cordova1/f00000.png
I can see the picture.Please help me. Thank you.
This question might better be answered by Mohamed Aly, the guy who actually worked on this. His contact is right on the page you linked.
That said, let's take a look. (There's a TLDR if you want to skip this) The error is caused by the cvGetMat in the cxarray.cpp file. The first couple lines of which are:
2362 cvGetMat( const CvArr* array, CvMat* mat,
2363 int* pCOI, int allowND )
2364 {
2365 CvMat* result = 0;
2366 CvMat* src = (CvMat*)array;
2367 int coi = 0;
2368
2369 if( !mat || !src )
2370 CV_Error( CV_StsNullPtr, "NULL array pointer is passed" );
...
return result;
}
It isn't until later that we actually check if you're image has data in it or not.
So now lets find where Mr. Aly used cvGetMat(). We're in luck! Only one place where he's used it without commenting it out: File is mcv.cc
void mcvLoadImage(const char *filename, CvMat **clrImage, CvMat** channelImage)
{
// load the image
IplImage* im;
im = cvLoadImage(filename, CV_LOAD_IMAGE_COLOR);
// convert to mat and get first channel
CvMat temp;
cvGetMat(im, &temp);
*clrImage = cvCloneMat(&temp);
// convert to single channel
CvMat *schannel_mat;
CvMat* tchannelImage = cvCreateMat(im->height, im->width, INT_MAT_TYPE);
cvSplit(*clrImage, tchannelImage, NULL, NULL, NULL);
// convert to float
*channelImage = cvCreateMat(im->height, im->width, FLOAT_MAT_TYPE);
cvConvertScale(tchannelImage, *channelImage, 1./255);
// destroy
cvReleaseMat(&tchannelImage);
cvReleaseImage(&im);
}
This is clearly where the filename you specified ends up. Nothing wrong here. It would be nice if he double-checked that the image was actually loaded in the code, but not strictly necessary. The cvGetMat has two inputs, the image, and the mat it gets written into. The mat should be fine, so we need to check the image. cvLoadImage would work with any filename - whether or not the file exists - without giving an error; so we need to check that the filename got there intact. mcvLoadImage is called in ProcessImage(*) in the main.cc file - but this also gets the filename passed into it. ProcessImage is called in Process() where the filename is put in as the same string that is printed out when it says
Processing image: /home/me/caltech-lanes/cordova1/f00000.png
Of course, that's just a string - he didn't check if he could read in the file beforehand, so when he say "Processing Image" he really means "This is the path I was given to the image - but I don't actually know if I can read it yet".
TLDR: (And I can't blame ya) So it seems like the main issue is that it can't read the file despite eog being able to display it. As-is the only thing I can suggest is trying to move the folder cordova1 to something like C:/Test/cordova1/ or (if there are settings on your computer that prevent that from working) C:/Users/[You]/cordova1/ with the files in there and do a
$ ./LaneDetector32 --show --list-file=/home/me/caltech-lanes/cordova1/list.txt --list-path=/home/me/caltech-lanes/cordova1/ --output-suffix=_result
to see if it's a permissions error preventing the lane-detection program from actually reading in the file.
Just in case it helps, I had this same error because I was dealing (trying to show) with very large images.
So I had to segment the images and process it chunk by chunk.
(I was using OpenCV 3.0 for Python, I know this was for C++ but it is basically what is running underneath).

cvLoadImage for IplImage working, but cv::imread for cv::Mat not workign

I am facing a weird issue where I am unable to read a basic image file from the filesystem using cv::imread. Hence the below results into imageInput having null data, with rows and cols set to 0.
cv::Mat imageInput = cv::Mat();
imageInput = cv::imread("abc.jpg",cv::IMREAD_COLOR);
Interestingly, after commenting out the above code, the below code is able to read the iamge:
//cv::Mat imageInput = cv::Mat();
//imageInput = cv::imread("abc.jpg",cv::IMREAD_COLOR);
IplImage *rImg;
rImg = cvLoadImage("abc.jpg", CV_LOAD_IMAGE_COLOR);
rImg gets a width of 3296, and height of 2256 as expected.
I am clueless how this is possible. Please help.
The build seems to be fine in both cases. I tried using both opencv-2.4.5 and opencv-2.4.6
I have been able to figure out the issue now.
The issue was mention of release build static libraries instead of debug-build static libraries.
Earlier for the VC++ project, I was including the following lib dependencies in debug mode : opencv_core245.lib;opencv_highgui245.lib;opencv_imgproc245.lib;opencv_video245.lib
Upon changing it to opencv_core245d.lib;opencv_highgui245d.lib;opencv_imgproc245d.lib;opencv_video245d.lib, I am able to read images using imread without any issues.