Trying to learn OpenCV 4.3 w/C++ & Visual Studio 2019 and starting with unknown error

Typed the Code directly out of the book. I get no errors, warnings, or messages. When I run program to read/write/show image, the window opens and shuts immediately without showing picture (and to fast to read any content). I used the photo (lena.jpg) that installed with OpenCV using the absolute address. The program exits with: “The program ‘[3192] Cpt2ReadWriteImage.exe’ has exited with code -1 (0xffffffff).” I’m assuming it did not find the photo. Any assistance appreciated by this newbie!

//System includes
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

//OpenCV includes
#include <opencv2\core\core.hpp>
#include <opencv2\highgui.hpp>
//#include <opencv2\imgcodecs.hpp>
using namespace cv;

int main(int argc, const char** argv)  //main program
{
	//Read image

	Mat color = imread("../lena.jpg");
	Mat gray = imread("../lena.jpg"), CV_LOAD_IMAGE_GRAYSCALE;

	//check for invalid input
	if (!color.data)
	{
		cout << "Could Not open or find the image" << std::endl;
		return -1;
	}

	//Write images
	imwrite("lenaGray.jpg", gray);
	//Get same pixel with opencv function
	int myRow = color.cols - 1;
	int myCol = color.rows - 1;
	Vec3b pixel = color.at<Vec3b>(myRow, myCol);
	cout << "Pixel value (B,G,R):(" << (int)pixel[10] << "," <<
(int)pixel[1] << "," << (int)pixel[2] << "," << endl;

	//Show images
	imshow("Lena BGR", color);
	imshow("Lena Gray", gray);

	//wait for any key pressed
	waitKey(0);
	return 0;
}

I reformatted your code to use syntax highlighting (use three backticks before and after the whole block, and say C++ right after the first three backticks, like “```C++”)

you are having issues that are more basic than OpenCV.

the window that pops up briefly is a console window. look on the internet how you can make Visual Studio keep it open regardless, or manually run the program in a separate terminal window (cmd.exe).

advice from the internet: https://stackoverflow.com/questions/454681/how-to-keep-the-console-window-open-in-visual-c

hacks like “just use getchar()” don’t work in the important situations (when you have an error). if you see that mentioned, ignore it.

Visual Studio can run that program in a tab inside of VS instead of its own console window

you need to figure that out first. you won’t see errors otherwise.

use forward slashes in include paths. backslashes are for escaping.

your second imread's syntax is wrong. the flag parameter belongs inside the parens.

you say pixel[10] when you meant pixel[0]

Thanks! I’ll give it a try!
Bob

by the way, I would agree with you that you’re hitting the “Could Not open or find the image” and return -1 branch of the code. the program could exit with -1 in some other way but assuming no other issues, that would be it.

the path to your image is relative. that’s okay but requires the process to have the right “working directory”, which can be different from where the source file is, or even where the executable is. Visual Studio may be responsible for that. to print the current working directory, try this (example at the end) https://en.cppreference.com/w/cpp/filesystem/current_path

Ok, I tried the suggestion regarding path for working dir. Had no problem with the “include” statement, but system did not find the fs namespace as shown in the example you send or just simplified… using namespace fs;
The program now stops at the window and says, “Could Not open or find the image”. It appears I’m stuck on the “path” problem. Still working on it though! Thanks!!
Bob

1 Like

ah right, the current_path link I gave is only C++ 17 onwards. I think you can ask VS for that, but that’s a different issue.

if you want to bypass the issue, just give an absolute path for now. in windows explorer, hold shift while right-clicking on the picture file. you’ll get a hidden menu item called “Copy as path”. that’s the path. you’ll need to turn \ into \\ because C/C++ string literals treat \ special, like "C:\\Users\\User\\Desktop\\picture.jpg"

you can try a little bit of winapi

#include <Windows.h>
...
char buf[MAX_PATH];
int length = GetCurrentDirectoryA(MAX_PATH, buf);
cout << "current directory: " << buf << " (" << length << " characters)" << endl;

since I need to dust off my C++ anyway, here’s some more code:

#include <Windows.h>
#include <iostream>
#include <vector>

using namespace std;

int main(void) // that's valid actually
{
	int length = 0; // need that a bunch of times

	// (1) plain old C array

	char buf[MAX_PATH];
	length = GetCurrentDirectoryA(MAX_PATH, buf);
	cout << "current directory (C array):\n\t" << buf << " (" << length << " characters)" << endl;

	// (2) C array, then to C++ string

	std::string str2(buf, buf + length); // "iterator", pass begin and end
	cout << "current directory (C++ string from array):\n\t" << str2 << " (" << length << " characters)" << endl;

	// (3) C++ vector, to C++ string

	std::vector<char> vec(MAX_PATH, 0); // will be initialized even if we don't need to
	length = GetCurrentDirectoryA(MAX_PATH, vec.data());

	//vec.resize(length);
	//string str3(vec.begin(), vec.end());
	// or just...
	std::string str3(vec.begin(), vec.begin() + length);

	cout << "current directory (C++ vector to string):\n\t" << str3 << " (" << length << " chars)" << endl;

	// (4) can't write directly into a std::string's data() because C++ needs to be special

	return 0;
}

Thanks for all the assists! I’ll give this info a try tomorrow! Will keep you appraised! Thanks!
Bob

You code worked fine and I got the “working directory”. Thanks! (apparently your C++ wasn’t to dusty after all!!)
I cut and pasted the listed Directory after I placed the “lena.jpg” file in that dir.
Unfortunately, the program still does not find it. Although the window that pops up is definitely the right one as I changed the wording to use if file not found and that was what showed. Hmmm.

Here’s the latest… I got the program to work. It shows both pictures, but they are both in color. I believe error is being caused in the line:

Mat gray = imread(“D:/lena.jpg”, CV_LOAD_IMAGE_GRAYSCALE); //direct copy from book

Mat gray = imread(D:/lena.jpg"), CV_LOAD_IMAGE_GRAYSCALE; //what is actually coded into program, as book version was wrong and created numerous errors.

Unfortunately, while the program runs with that change, it does not gray scale the second photo. I’m starting to think that there may have been a change in OpenCV 4.3’s “CV_LOAD_IMAGE_GRAYSCALE” syntax that I haven’t found yet!

book version is right but outdated. the constant is now IMREAD_GRAYSCALE.

the second one is definitely wrong, but the compiler doesn’t complain because what you wrote is technically a legal expression… with no effect from the constant.

take your constants from this:

Once again, THANKS!! The book copyright in Sept, 2019! Guess the authors are set in their ways! I’ll change it the code tomorrow.
B.

1 Like

That did the trick! Thanks for the help!