EM algorithm, read and save XML file - c++

I want to save my classifier, and then when I am trying to read it back, it throws segmentation error. I tried to figure it out, and I think it is a bug with opencv.
Here is my code:
bool result = model.train(samples,Mat(),ps,&lables);
printf("Train Result %d\n",result);
CvFileStorage *fs;
fs = cvOpenFileStorage("skin_new.xml",NULL, CV_STORAGE_WRITE);
model.write_params(fs);
cvReleaseFileStorage( &fs );
CvFileStorage *fs1;
//Reading back XML file
fs1 = cvOpenFileStorage("skin_new.xml",NULL , CV_STORAGE_READ);
classifier.read_params(fs1,NULL);
cvReleaseFileStorage( &fs1 );
printf("XML reading done\n");
//the two dominating colors
Mat means = model.getMeans();//This step leads to segmentation error
I'm using OpenCV 2.3.1.

I think you are developing in Linux OS. So I think you don't have the access permission to the skin_new.xml file.
You can use
chmod 777 skin_new.xml
But it's temporary. I'm facing the same problem as well.

Related

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.

CImg loading image fails with spaces in path name

I have a C++ application that I am developing to scan an image and return coordinates, the whole application works as expected except for this last problem that I can't seem to figure out. a user uploads images to a folder, and then the images get run one at a time to the application in a queue. well the problem is, that we have thousands of users with many folders, and a good amount of these users upload folder/files with a space (ex: " "), in the folder/file name.
When the application runs it crashes, I have narrowed it down to the fact that CImg does not like spaces in the path.
Every time it runs on my local machine with a space in the path I get the following error, which doesn't seem to say much.
Unhandled exception at 0x00BE05F7 in jpeg-info.exe: 0xC00000FD: Stack overflow >(parameters: 0x00000000, 0x00242000).
[CImg] * CImgIOException * [instance(0,0,0,0,00000000,non-shared)] CImg::load(): Failed to open file 'J:\uploads\41039\test name'
[CImg] * CImgIOException * cimg::fopen(): Failed to open file 'J:\uploads\41039\test name' with mode 'rb'.
the line of code it fails on is here.
const char* imagePath = filename.c_str();
CImg<unsigned char> loadImage(imagePath);
I just need to figure out a way to pass a path to CImg with spaces in the string and it not break.
Sidenote: I do have the boost filesystem installed if that makes it any easier to figure out this solution.
EDIT:
I was getting the filename two different ways with not luck on fixing this issue..
original way: (passing const char directly)
const char* filename = cimg_option("-i", "path/to/file/jpeg.jpg", "input jpeg path");
new way: (grabbing path and using boost to format it properly)
const char* getInput = cimg_option("-i", "path/to/file/jpeg.jpg", "input jpeg path");
std::string filename = boost::filesystem::absolute(getInput).string();

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).

Error loading cr2 with edsdk

I am trying to read cr2 images using canon sdk (canon_edsdk-2.12).
I seem to be loading the dll correctly, but when I try to get the actual image, I get an error.
I tried to run the sample program to see how that is different than mine, but the same thing happens.
Trying to look for the issue on the web, I found the actual source code of the sample: http://read.pudn.com/downloads107/sourcecode/graph/texture_mapping/440409/RAWDevelop/RAWDevelopDlg.cpp__.htm
My error, on the given source, is in the void CRAWDevelopDlg::LoadImage() function -
err = EdsGetImage( m_ImageRef , source , kEdsTargetImageType_RGB , rect , size , DstStreamRef );
if( err == EDS_ERR_OK ) {...}
else
{
AfxMessageBox("The error occurred with the EdsGetImage function.");
}
The above (on line 481 on the page) is the same method that I use, and i get the same error - with error code 35 (instead of 0).
The error seems to be
#define EDS_ERR_FILE_OPEN_ERROR 0x00000023L
So... could there be something wrong with the files ? I experimented with files taken by different versions, including the newest cameras... The files open in Photoshop... And the demo does show header information, as it gives the error. So it can see something.
Am I missing anything ?
All the required dll's used are on the system path...
Thank you.
Old question, still, might help someone:
To open a raw file with the SDK you need to call these functions (you should check for errors, of course):
EdsStreamRef stream = NULL;
EdsImageRef imgRef = NULL;
EdsCreateFileStream("filename", kEdsFile_OpenExisting, kEdsAccess_Read, &stream);
EdsCreateImageRef(stream, &imgRef);
EdsRelease(stream);
Then you can set and get properties with the imgRef.
To save the image as jpg/tiff/RGB image use EdsSaveImage function.