I'm having a problem with OpenCV and the Assertion failed error. It seems to be having a problem reading the image so the function imread() fails silently and then in resize() function it crashes because the input image is empty.
I've checked the path and it's ok, in fact if I print the path that I'm trying to read and do open path in a terminal image opens just fine. Also, if I take this path that I printed and put it in a string variable code works. So the problem seems to be with ss object. I just don't know what.
Here's my code:
int main(int argc, char** argv ){
cout << "Prueba OpenCV \n";
char* path;
Mat input;
if(argc >= 2 )
{
path = argv[1];
for(int j=0; j< numFiles; j++){
cout << "Character "<< OCR::strCharacters[1] << " file: " << j << "\n";
stringstream ss(stringstream::in | stringstream::out);
ss << path << OCR::strCharacters[1] << "/" << j << ".jpg" << "\n";
cout << "Character file: " << ss.str() << "\n";
Mat img=imread(ss.str(), 0);
/*if (img.cols == 0) {
cout << "Error reading file " << ss << endl;
return -1;
}*/
Mat lowData;
resize(img, lowData, Size(5, 5) );
}
}
}
run this with:
./PruebaOpenCV samples/
I found this link in stack that had a similar problem but the answer just was a piece of code to know if the image is properly read (commented code above). I know mine isn't but path is ok.
Related
I have a project where part of it is processing a video as a batch of images. I found a snippet online which helped me process a batch of images(the one attached below)
string Img_seq[] = {"flying_plane"};
int size_of_Img_seq = sizeof(Img_seq) / sizeof(Img_seq[0]);
imgpath = argv[1];
if (argc >= 3)
{
TrackingResPath = argv[2];
cout << "The image path is: " << imgpath << endl;
int Seg_num = 1; //for OPE
for (int j = 0; j < size_of_Img_seq; ++j)
{
folder = imgpath + Img_seq[j] + "/*.jpg";
string imgInFormat, imgOutFormat, imgOutFormat1, imgOutFormat2;
ofstream outBB;
imgInFormat = imgpath + Img_seq[j] + "/%05d.jpg";
if (argc >= 3)
{
//add process here
}
}
// get the total number of images in folder
glob(folder, filenames);
int Frames_per_seg = filenames.size(); // for OPE
cout << "Frames_per_seg = " << Frames_per_seg << endl;
for (int k = 1; k <= Seg_num; ++k)
{
sprintf(imgInPath, imgInFormat.c_str(), startFrame);// read image path
sprintf(imgOutPath, imgOutFormat.c_str(), startFrame);
}
I need to use this procedure to process a video from either a directory or from the webcam. I tried the one way which I've given below but it is spitting out errors
VideoCapture capture(videoFilename);
if(!capture.isOpened()){
cerr << "Unable to open video file:" << videoFilename << endl;
exit(EXIT_FAILURE);
}
while( (char)keyboard != 'q' && (char)keyboard != 27){
if(!capture.read(frame)){
cerr << "Unable to read next frame" << endl;
cerr << "Exiting" << endl;
exit(EXIT_FAILURE);
}}
stringstream ss;
rectangle(frame, cv::Point(10, 2), cv::Point(100, 20),
cv::Scalar(255, 255, 255), -1);
ss << capture.get(CV_CAP_PROP_POS_FRAMES);
string Img_seq[] = ss.str();
keyboard = waitKey( 30 );
The errors are basically because Img_seq[] is not linked properly between the above two codes.
Could anyone help me understand how I should proceed in using video for a batch processing logic.
I want to convert stereo images captured by Basler cameras to opencv (Mat) format. In the below code i have converted images to opencv format, but in show stages, i can not show the images. please guide me.
Thanks
int main(int argc, char* argv[])
{
// The exit code of the sample application.
int exitCode = 0;
PylonInitialize();
Pylon::PylonAutoInitTerm autoInitTerm;//me
try
{
// Get the transport layer factory.
CTlFactory& tlFactory = CTlFactory::GetInstance();
// Get all attached devices and exit application if no device is found.
DeviceInfoList_t devices;
if (tlFactory.EnumerateDevices(devices) == 0)
{
throw RUNTIME_EXCEPTION("No camera present.");
}
CInstantCameraArray cameras(min(devices.size(), c_maxCamerasToUse));
// Create and attach all Pylon Devices.
for (size_t i = 0; i < cameras.GetSize(); ++i)
{
cameras[i].Attach(tlFactory.CreateDevice(devices[i]));
// Print the model name of the camera.
cout << "Using device " << cameras[i].GetDeviceInfo().GetModelName() << endl;
}
CGrabResultPtr ptrGrabResult;
CImageFormatConverter formatConverter;//me
formatConverter.OutputPixelFormat = PixelType_BGR8packed;//me
CPylonImage pylonImage;//me
// Create an OpenCV image
Mat openCvImage;//me
for (int i = 0; i < c_countOfImagesToGrab && cameras.IsGrabbing(); ++i)
{
cameras.RetrieveResult(5000, ptrGrabResult, TimeoutHandling_ThrowException);
intptr_t cameraContextValue = ptrGrabResult->GetCameraContext();
#ifdef PYLON_WIN_BUILD
#endif
// Print the index and the model name of the camera.
cout << "Camera " << cameraContextValue << ": " << cameras[cameraContextValue].GetDeviceInfo().GetModelName() << endl;
// Now, the image data can be processed.
cout << "GrabSucceeded: " << ptrGrabResult->GrabSucceeded() << endl;
cout << "SizeX: " << ptrGrabResult->GetWidth() << endl;
cout << "SizeY: " << ptrGrabResult->GetHeight() << endl;
const uint8_t *pImageBuffer = (uint8_t *)ptrGrabResult->GetBuffer();
cout << "Gray value of first pixel: " << (uint32_t)pImageBuffer[0] << endl << endl;
formatConverter.Convert(pylonImage, ptrGrabResult);//me
// Create an OpenCV image out of pylon image
openCvImage = cv::Mat(ptrGrabResult->GetHeight(), ptrGrabResult->GetWidth(), CV_8UC3, (uint8_t *)pylonImage.GetBuffer());//me
if (cameraContextValue == 0)
{
imshow("left camera", openCvImage);
imwrite("right_img.png", openCvImage);
}
else if (cameraContextValue == 1)
{
imshow("right camera", openCvImage);
imwrite("right_img.png", openCvImage);
}
Sleep(3000);
}
}
catch (const GenericException &e)
{
// Error handling
cerr << "An exception occurred." << endl
<< e.GetDescription() << endl;
exitCode = 1;
}
// Comment the following two lines to disable waiting on exit.
cerr << endl << "Press Enter to exit." << endl;
while (cin.get() != '\n');
// Releases all pylon resources.
PylonTerminate();
return exitCode;
}
You need to create a window to display an opencv image into, use :
namedWindow("left camera", CV_WINDOW_NORMAL);
imshow("left camera", openCvImage);
There is also a few mistakes in your code, i guess "right_img.png" should be change in "left_img.png", otherwise you will save only one image.
And this is redundant code
PylonInitialize();
Pylon::PylonAutoInitTerm autoInitTerm;
autoInitTerm is automatically calling PylonInitialize() and PylonTerminate(). So you should remove it or remove PylonInitialize() and PylonTerminate()
I think a waitKey(0) is required after the imshow to display the image.
add below piece of code. after completing for (size_t i = 0; i < cameras.GetSize(); ++i)
cameras.StartGrabbing(GrabStrategy_LatestImageOnly, GrabLoop_ProvidedByUser);
Add this to your code. and like above comments remove unnecessary code.
I am trying to create a json file from c++. The used code is the following:
Mat projected = eigenfacesExtraction(fileName);
ofstream myfile;
myfile.open ("detection.json");
myfile << "{\n";
myfile << "\t \"meta\":{\n";
myfile << "\t \"duration\":\""<<duration<<"\",\n";
myfile << "\t \"fileName\":\""<<fileName<<"\"\n";
myfile << "},\n";
myfile << "\t \"num_of_people\":\""<< faces.size()<<"\",\n";
myfile << "\t \"faces\":[\n";
myfile << "\t \"projected\":[" << projected.size <<"] ,\n";
for(int i=0; i<faces.size(); i++){
if(!faces.empty()){
if(i!= faces.size()-1){
myfile << "\t \"coord\":\" \t[" << faces[i].x << ", "<<faces[i].y<< ", "<< faces[i].width << ", "<<faces[i].height<<"],\n";
myfile << "\t \"descr\":\" \t[" << projected.at<double>(0,1) << ", "<<projected.at<double>(0,2)<< ", "<< projected.at<double>(0,3) << ", "<<projected.at<double>(0,4)<<"],\n";
}
else myfile << "\t \"coord\":\" \t[" << faces[i].x << ", "<<faces[i].y<< ", "<< faces[i].width << ", "<<faces[i].height<<"]\n";
myfile << "\t \"descr\":\" \t[" << projected.at<double>(0,1) << ", "<<projected.at<double>(0,2)<< ", "<< projected.at<double>(0,3)<< ", "<<projected.at<double>(0,4)<<"],\n";
}
}
myfile << "]\n";
myfile << "}";
myfile.close();
cout<< "Detection process exits...."<<endl;
//imwrite( "/opencvAssets/results/"+fileName, image );
imwrite("outputCapture.jpeg", image);
//waitKey(0);
//imshow("cropped image", croppedFaceImage);
My program works fine, json file is stored properly also cout prints the message, but I am receiving the following message "Segmentation fault (core dumped)". When I comment out iwrite command neither json nor cout work and I am receiving again the same message. What is the matter here?? The eigenFacesExtraction function (which may cause the problems) is the following:
Mat Detection::eigenfacesExtraction(string fileName){
Ptr<FaceRecognizer> model = createEigenFaceRecognizer();
model->load("eigenfaces.yml"); // Load eigenfaces parameters
Mat eigenvalues = model->getMat("eigenvalues"); // Eigen values of PCA
Mat convMat = model->getMat("eigenvectors"); //Convariance matrix which contains eigenvectors
Mat mean = model->getMat("mean"); // Mean value
convMat.convertTo(convMat, CV_32F);
mean.convertTo(mean, CV_32F);
string path = fileName;
Mat sample ,pca_ed_sample, resizedSample;
sample = imread(path, CV_LOAD_IMAGE_GRAYSCALE);
sample.convertTo(sample, CV_32F);
resize(sample,resizedSample,Size(60,60),0,0,INTER_LINEAR);
Mat nu = resizedSample.reshape(1,3600).t();
pca_ed_sample = (nu-mean)*(convMat);
return pca_ed_sample;
}
Segmentation fault occurs when we try to change only readable memory or when we try to access the memory out of your program boundaries. Place it in a debugger and trace it thoroughly. For more information chech this stackoverflow question
What is a segmentation fault?
For some reason, it just won't load the mesh file. I can't tell if its because Im entering something wrong, or if I just dont have the file in the right folder. I have it in the same folder as the .exe right now, and I have it under my "source files" too (that could be wrong).
Mesh.cpp
#include "MeshTable.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
void MeshTable::ReadMesh_M(const char *filename) {
points.clear();
faces.clear();
//the Vertex id in .m file begins from 1,
//we insert an empty point to align the index
points.push_back(Point());
std::ifstream input("C:\\Users\\Zach\\Documents\\Visual Studio 2010\\Projects\\MAIN\\Release\\dog.m");
while(input.good()) {
std::string line;
getline(input, line);
if (line.empty()) {
continue;
}
std::stringstream ss(line);
std::string title;
int id;
ss >> title;
if (title == "Vertex") {
Point pt;
ss >> id >> pt[0] >> pt[1] >> pt[2];
points.push_back(pt);
}
else if (title == "Face") {
Face face;
ss >> id >> face.pt_ids[0] >> face.pt_ids[1] >> face.pt_ids[2];
faces.push_back(face);
}
}
input.close();
}
void MeshTable::SaveMesh_M(const char *filename) {
std:: ofstream output(C:\\Users\\Zach\\Documents\\Visual Studio 2010\\Projects\\MAIN\\Release\\dog_out.m);
for (unsigned int i = 1; i < points.size(); ++i) {
const Point& pt = points[i];
output << "Vertex " << i << " " << pt[0] << " " << pt[1] << " " << pt[2] << "\n";
}
for (unsigned int i = 0; i < faces.size(); ++i) {
const Face& face = faces[i];
output << "Face " << i + 1 << " " << face.pt_ids[0] << " " << face.pt_ids[1] << " " << face.pt_ids[2] << "\n";
}
output.close();
}
It builds fine, but when I try to debug it, the OpenGL window pops open for like 3 seconds and then closes and says "The program '[3188] Main.exe: Native' has exited with code -1 (0xffffffff)." Which comes from my main.cpp.
if (argc != 2) {
std::cout << "Load a .m file as a mesh table.\n";
std::cout << "Usage: " << argv[0] << " input_mesh.m\n";
exit(-1);
}
EDIT Once I deleted this, it worked. My teacher gave me this (part) of the code so I dont really understand why that would make it not work.
if (argc != 2) {
std::cout << "Load a .m file as a mesh table.\n";
std::cout << "Usage: " << argv[0] << " input_mesh.m\n";
exit(-1);
}
if (argc != 2) {
std::cout << "Load a .m file as a mesh table.\n";
std::cout << "Usage: " << argv[0] << " input_mesh.m\n";
exit(-1);
}
You need to pass name of mesh file into command line parameter when you run the program. I.e. it should be launched as "program.exe meshfile.m".
In VS 2008 debugging parameters/command line arguments could be specified in project properties->configuration properties->debugging->command arguments. In VS2010 they could be in similar locations.
Also, read "output" when you run the program. Code fragment provided by your teacher actually prints program usage.
I have have the following problem:
When I drag and drop a file to my tool (exe) when ifstream fails to open the file.
If I give it manually though the console it works!
I don't get where the diffenence is, because I am cutting the path and passing just the filename.
Have a look at the code:
int main(int argc, char* argv[]) {
if (argc < 2) {
cout
<< "ERROR: Wrong amount of arguments! Give at least one argument ...\n"
<< endl;
cout << "\n" << "Programm finished...\n\n" << endl;
cin.ignore();
exit(1);
return 0;
}
vector<string> files;
for (int g = 1; g < argc; g++) {
string s = argv[g];
cout<<"parameter at: " << g << " = " << argv[g] << "\n" << endl;
string filename = "";
int pos = s.find_last_of("\\", s.size());
if (pos != -1) {
filename.append(s.substr(pos + 1));
// cout<<" cutted path: " << s.substr(0,s.size()-filename.size()) << endl;
// cout << "argv[1] " << argv[1] << endl;
cout << "\n filename: " << filename << "\t pos: " << pos << endl;
files.push_back(filename);
}
files.push_back(s);
}
for (unsigned int k = 0; k < files.size(); k++)
{
cout << "files.at( " << k << " ): " << files.at(k).c_str() << endl;
Converter a(files.at(k).c_str());
a.getCommandsFromCSV();
a.saveConvertedFile();
}
cout << "\n" << "Programm finished...\n\n" << endl;
cin.ignore();
return 0;
}
It fails already on the constructor:
Converter::Converter(const char* file) {
filename = file;
myfile.open(filename.c_str(), ios_base::in);
cout << (myfile ? "open successful on constructor " : "some error on constructor");
cin.ignore();
trace_raw = "";
}
You have any idea why?
UPDATE:
The file as parameter works now. The solution was to leave the full path.
Anyway I have the same error on a hard coded file. I thought it may be the same that's why I added .\ at the beginning of the file name... without success.
The code:
void GenericCommandConverter::getATCommandsFromCSV() {
cout << "\t| +++++++++++getATCommandsFromCSV() started+++++++++++++ |"
<< endl;
/*
* CSV file name is hardcoded
*/
string filename_csv = ".\\test.csv";
string commands = "";
int pos_start = 0;
int pos_end = 0; // "|"
int substrLength = 0;
int separator_count = 0;
char c;
vector<string> lines;
vector<string> commandList;
vector<vector<string> > linesSeparated;
ifstream csvFile;
csvFile.open(filename_csv.c_str(), ios_base::in);
cout << (myfile ? "open successful on getATCommandsFromCSV " : "some error on getATCommandsFromCSV ");
cin.ignore();
...
UPDATE2:
The solution was: on dropping a file to the exe, the "root" folder changes to the one where the dropped file comes from. Giving the hardcoded file the path from the *.exe solved it!
I am guessing your current directory is wrong. Don't cut the path off. Anyway you should do error checking / debugging to see why it couldn't open the file. Diligent debugging is essential for solving problems without having to make blind guesses.