Encountered Segmentation fault in simple OpenCV code - c++

Tools
Platform : 64-bit Windows
Compiler chain: mingw with Qt
Make system: CMake
Libraries: C++ 11, OpenCV 4, Qt 5
Problem (Updated)
The following simple program segment should compile and display the generated image in OpenCV. However, it always SIGSEGVs in DEBUG mode only(Backtrace at the end). However, it works just fine in RELEASE mode.
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
void testOPENCV()
{
cv::Mat output(480, 640, CV_8UC3, cv::Scalar(255,0,100));
cv::namedWindow( "Test", cv::WINDOW_AUTOSIZE );
cv::imshow("Test",output);
cv::waitKey(0);
}
int main(int argc, char** argv)
{
testOPENCV();
return 0;
}
I have a CMake script that builds only the required OpenCV modules and links these to the dependencies. The relevant part:
build_external_project(opencv "https://github.com/opencv/opencv.git" "4.2.0" "-DCMAKE_INSTALL_PREFIX=${THIRDPARTY_INSTALLFOLDER} - DCMAKE_BUILD_TYPE=${THIRDPARTY_BUILDTYPE} -DBUILD_LIST=core,imgproc,imgcodecs,highgui")
target_link_libraries(OpenVideo ${OpenCV_LIBS})
The binary can be run with no missing dll errors. Dependency walker also indicates the same.
Here is the backtrace:

Given that OpenCV works fine in Release mode, I suggest rebuilding the Debug version of the library.
Previous answer:
There are a few potential problems with your code:
Using Qt is unnecessary on this example and it adds a complexity that you don't need right now. Remove it from the project and its libraries on the link instruction in the CMake script. Later, you can bring it back to see if it causes of the crash. Right now you need to pinpoint if the problem is in OpenCV or Qt.
An image can only be displayed on a window if cv::waitKey() is invoked;
The directory separator on Windows is usually \\ and not /;
This is the full source code to test your OpenCV build:
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
int main()
{
std::string file_name("C:\\Images\\1.jpg");
cv::Mat original_image = cv::imread(file_name, cv::IMREAD_COLOR);
if (original_image.empty())
{
std::cout << "!!! image not found" << std::endl;
return -1;
}
cv::imshow( "Display window", original_image );
cv::waitKey(0);
return 0;
}

Few things to check here.
First, where do the OpenCV library come from? Is it compiled for your CPU? Looks like it crashed in AVX instructions. Might be that CPU does not support them.
Second, not obvious at all, happened to me with .png files. Same segfault during runtime. Turned out that OpenCV was built without png support. Please check if your OpenCV built with -DWITH_JPEG=ON.

https://docs.opencv.org/2.4/doc/tutorials/introduction/display_image/display_image.html
You forgot to create window
namedWindow( "Display window", WINDOW_AUTOSIZE );// Create a window for display.

Adding to karlphillips answer: Deubg and Release behave quite differently on Windows than on Linux (due to runtime selection).
Especially if you link against release libraries on Windows but your libs or executable are being built in debug. If they use different runtimes you will be very likely run into issues and segfaults. So check the flags of both projects (typical culprits are flags like multithreading (debug) being present on one but not the other).

Related

openCV libraries call local path that does not exist

i am making a simple c++ program with openCV library included. Eclipse IDE recognises openCV commands and library locations, but when i try to build the project, compiler gives external error, referring to opencv.hpp or core.hpp file calling a "opencv2/core.hpp" path, which does not exist in opencv folder. I figured out that the problem is linked to the way core.hpp is called, but the library files are read-only.
From what i saw in opencv.hpp file, this relative "opencv2/[module].hpp" reference is not only for the core, but all other modules as well. There is no opencv2 folder inside the one to where openCV is installed at all, in fact.
I've tried reinstalling and remaking openCV with different making arguments, using a different IDE and including direct search folders in eclipse. The problem, apparently, lies in the files themselves, or the way it maybe gets installed in the system the wrong way. The problem persists on both my main ubuntu machine and the ARMbian orange pi.
i get this error when trying to include any openCV library that contains
#include "opencv2/[opencv module].hpp" in it
as a result, compilation is terminated with the error message stating "/usr/local/include/opencv4/opencv2/opencv.hpp:52:28: fatal error: opencv2/core.hpp: No such file or directory"
edit 1: GCC c++ compiler options are -Iusr/local/include/opencv4/opencv2 -O3 -Wall -c -fmessage-length=0 and linker's options are -L/usr/local/lib.
The code is a simple displayImage
#include <opencv4/opencv2/opencv.hpp>
#include <opencv4/opencv2/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
int main( int argc, char** argv )
{
Mat image;
image = imread( argv[1], 1 );
namedWindow( "Display Image", CV_WINDOW_AUTOSIZE );
imshow( "Display Image", image );
waitKey(0);
return 0;
}
edit 2: $ pkg-config --libs opencv does not see openCV as installed in the system, altho i've made sure to run make install and ldconfig on the path. This may be a signal of faulty installation, but this is just a sidenote, not entirely related to main problem. I have tried reinstalls and to different folders, but this also persists as well as a main problem
apparently, #sgarizvi 's comment was the answer. I just needed to set the include path to I/usr/local/include/opencv4 and it worked. After that, the error was fixed.
I am replying to my own question to close the case, as i cannot upvote/veryfy a comment
In your case, since your include path is /usr/local/include/opencv4/opencv2
Replace the first three lines
#include <opencv4/opencv2/opencv.hpp>
#include <opencv4/opencv2/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
by
#include <opencv.hpp>
#include <imgproc.hpp>
#include <highgui.hpp>

OpenCV 3.4.0 - zlibd1.dll was not found

I have the following program, which is the same as this tutorial page for OpenCV 3.4.0. I am using Visual Studio 2017 Community on a 64-bit laptop with Windows 10 Enterprise 64-bit.
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
if( argc != 2)
{
cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
return -1;
}
Mat image;
image = imread(argv[1], IMREAD_COLOR); // Read the file
if( image.empty() ) // Check for invalid input
{
cout << "Could not open or find the image" << std::endl ;
return -1;
}
namedWindow( "Display window", WINDOW_AUTOSIZE ); // Create a window for display.
imshow( "Display window", image ); // Show our image inside it.
waitKey(0); // Wait for a keystroke in the window
return 0;
}
With the includes and linker directories and libraries set up for this project, the solution builds just fine. But when I run the program, I get the following error:
"The code execution cannot proceed because zlibd1.dll was not found. Reinstalling the program may fix this problem."
From my initial research, it's not necessarily coming from Visual Studio 2017. When I try to create a new project, I do not have the option to select "Win32 Console Application." The project this source code sits in is of type Windows Console Application under Visual C++, supporting .NET Framework 4.5.
What am I missing here?
Based on the tutorial, I should be using only the libraries and the dynamic link libraries OpenCV 3.4.0 provides. I remember at one point using NuGET to try to install OpenCV 3.4.0 again, as explained here, when I was trying to solve the compiler error regarding fopen from a file within OpenCV 3.4.0 itself.
Okay, apparently it was a problem regarding my system path. It was not set right, Before, what I had was the path variable set to the following:
%OPENCV_DIR%\lib
%OPENCV_DIR%\bin
with $(OPENCV_DIR) being just the build directory of OpenCV 3.4.0.
But the directories there do not exist, and hence the libraries couldn't be found. So, I replaced them with this:
%OPENCV_DIR%\x64\vc15\bin
%OPENCV_DIR%\x64\vc15\lib
and the program now runs. What was I thinking back there?
Either way, important lesson to note: When you are getting a popup message saying the program cannot be opened because a library is missing, and is part of OpenCV 3.4.0, be sure that your system path in the Windows 10 System Advanced Settings is an OpenCV directory that exists.
This package has a problem to run under debug and result in zlibd1.dll problem. Switch to release if you can or use different nuget package.

OpenCV 2.4.2 imread function causing runtime error

I'm a starter in OpenCV. My programming environment is VC++ Express 2010 + OpenCV 2.4.2 + Win 7 64 bit.
I use purely 32bit configuration in my VC++ and Path.
I type in the following code:
#include "opencv2\highgui\highgui.hpp"
#include "opencv2\core\core.hpp"
using namespace cv;
int main(int argc, char** argv) {
char* imgPath = "logo.png";
Mat img = imread(imgPath);
namedWindow( "Example1", WINDOW_AUTOSIZE);
imshow("Example1", img);
waitKey(0);
return 0;
}
Then I compile and run. It does come up with a window (but without picture) but then gave me this (a runtime error?)
Unhandled exception at 0x770515de in Helloworld2.exe: Microsoft C++ exception: cv::Exception at memory location 0x001ef038..
Then I change the imread into cvLoadImage and it works without any errors.
Can someone tell me what's wrong?
I have tried the code you have given. It works perfectly fine with my installation of OpenCV.
However I am getting a warning at the line:
char* imgPath = "logo.png";
main.cpp:6:21: warning: deprecated conversion from string constant to 'char*' [-
Wwrite-strings]
Which i think is nothing serious to make the code crash, however it might be the problem in your case, as I am not using VC++ to compile.
What you can try to check if this is the issue is to replace imgPath with directly the string, so the code will now be like
Mat img = imread("logo.png");
I also got this issue, but I fixed it with the following. The point is using absolute path other than relative path, and change "\" with "/" in the file path.
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
int main() {
cv::Mat image = cv::imread("D:/projects/test/Debug/1.jpg");
if (image.empty()) {
return 0;
}
cv::namedWindow("my image");
cv::imshow("my image", image);
cv::waitKey(5000);
return 1;
}
The difference between cvLoadImage and imread can be seen on opencv documentation:
C++: Mat imread(const string& filename, int flags=1 )
and
C: CvMat* cvLoadImageM(const char* filename, int
iscolor=CV_LOAD_IMAGE_COLOR )
But there is an implicit conversion from const char * to string. As masad noted, this conversion is deprecated, so it is very compiler dependent.
As cvLoadImage works for you, it seems that you should change your code to something like this:
#include "opencv2\highgui\highgui.hpp"
#include "opencv2\core\core.hpp"
#include <string>
using namespace cv;
int main(int argc, char** argv) {
std::string imgPath("logo.png");
Mat img = imread(imgPath);
namedWindow( "Example1", WINDOW_AUTOSIZE);
imshow("Example1", img);
waitKey(0);
return 0;
}
There has been some problems with C++ interface in Visual Studio, but you may try to see if it works for you.
I had the same problem and I came across Installing OpenCV 2.4.3 in Visual C++ 2010 Express and it mentions to use the updated set of libraries *d.lib when adding dependencies for the Linker. I tried it and the C++ interface worked. Not sure if this is the case in general. I am using OpenCV 2.4 and Visual Studio 2010 on a 64 bit Windows machine.
I got the similar problem with you. When I use the imread function, the program crash with system error message:
opencv_debug.exe 中的 0x0036299f 处未处理的异常: 0xC0000005: 读取位置 0xcccccccc 时发生访问冲突
Then I change the imread into cvLoadImage and it works without any errors.
Finally, I fix the problem, it comes because I used VS2008 project with VS2010 compiled dll.
Here is my story.
Environment: VS2008 + opencv2.4.7
First, I just follow the link http://docs.opencv.org/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.html, and compile the my test project.
But, When I run my test project, the system error dialog tells me that I lost MSVCP100D.dll MSVCR100D.dll. So I download the two dll, the dll lost problem is solved, but the problem is crash on run time.
Notice that ahead link, it says:
it means that, in opencv2.4.7, they only provide dlls which compiled in vs2010 or vs2012, not vs2008.
When I compiling vs2008 project with dlls which compiled by vs2010, I get the wired problem.
How can I fix this problem?
use the older opencv version such as opencv2.3, this version contains the vs2008 compiled dll.
compile the opencv by yourself.
I have noticed that your environment is: VC++ Express 2010 + OpenCV 2.4.2 + Win 7 64 bit.
Be sure OPENCV_DIR is set right.
setx -m OPENCV_DIR D:\OpenCV\Build\x64\vc10

Can not read image with opencv2.3 imread

Hello I am trying to read an image by using imread function of opencv as in the link (http://opencv.itseez.com/doc/tutorials/introduction/display_image/display_image.html#display-image). I have VS2010 with 64 bit windows 7. Each time I try I get error message "no image data", however the image I want to read is in the same folder with codes. Can someone please help me how to read an image with imread function? My code is as below:
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
using namespace cv;
int _tmain(int argc, _TCHAR* argv[])
{
Mat image;
image = imread("al.jpg");
if(argc != 2 || !image.data )
{
printf("no image data \n");
return -1;
}
namedWindow("Display Image", CV_WINDOW_AUTOSIZE);
imshow("Display Image", image);
waitKey(0);
return 0;
}
It you can load image using
IplImage *img=cvLoadImage("Image_Name);
Then you can convert this into cv::Mat using,
Mat mat(img);
I've had the same problem on WinXP with VS2005 and OpenCV 2.3. It seems that the C++ interface of OpenCV is not working well for Windows. I also had problems with imread(), which returned NULL data.
I solved the problem using the C interface of OpenCV instead. For more info, check Reading and Writing Images and Video.
I have met the same problems as yours. The C++ interface for OpenCV2.3 didn't work and some functions have to convert to C version.
But at last, I found what the ** problem is.
That is because the project properties when you compiled your OpenCV source code with CMake, is not the same as your current project properties.(May be your OpenCV's dll and libs are download from the internet, and these may be compiled with other wierd properties.)
So I check my CMake generated OpenCV source code project, I found the project property , C/C++-->Code Generation, the Runtime Library is Multi-threaded Debug DLL(/MDd).
Then, I change the corresponding property in my current project, and my project work well. At the same time, the other C++ interface for OpenCV bugs is solved well.
Take out the argc != 2 test. You aren't using the arguments passed to your program so it's superfluous. And if argc is, in fact, not eaual to 2, your program is terminating before even getting to the !image.data test.
Edit: I just looked at the code sample you linked to. It loads an image whose name is passed to the program on the command line. That's why the argc != 2 test is there. You definitely want to take that out because you are most likely not passing a file name on the command line so your argc is 1, thus the test will always fail.
OpenCV offers support for the image formats Windows bitmap (bmp), portable image formats (pbm, pgm, ppm) and Sun raster (sr, ras).
I experience that same problem, This may come from VS project compilation in VS 10.
In visual studio 2010:
Go to project --> properties --> Character set --> Use multi byte instead of unicode.
Set the Common Language Runtime Support (/clr) in Visual C++.
It works.

Difficulties configuring openCV library in Visual C++

I'm trying to configure my Visual C++ to use the openCV libraries. I've followed the instructions on OpenCV website http://opencv.willowgarage.com/wiki/VisualC%2B%2B...
// OpenCV_Helloworld.cpp : Defines the entry point for the console application.
// Created for build/install tutorial, Microsoft Visual Studio and OpenCV 2.2.0
#include "stdafx.h"
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
int _tmain(int argc, _TCHAR* argv[])
{
// Open the file.
IplImage *img = cvLoadImage("photo.jpg");
if (!img) {
printf("Error: Couldn't open the image file.\n");
return 1;
}
// Display the image.
cvNamedWindow("Image:", CV_WINDOW_AUTOSIZE);
cvShowImage("Image:", img);
// Wait for the user to press a key in the GUI window.
cvWaitKey(0);
// Free the resources.
cvDestroyWindow("Image:");
cvReleaseImage(&img);
return 0;
}
I have altered the include and library directories in VC++ directories inside the Property Pages, and have added the additional dependencies. However, when I try and load an image with the same header files as the sample code, it says that cvLoadImage is undefined, as is cvNamedWindow
IplImage *img = cvLoadImage("JellyFish.jpg");
Any suggestions as to where I might have my problem?
You might try making sure your Code Generation for your project is Multi-threaded DLL (or Multi-threaded Debug DLL).
You need to configure using CMake. Get OpenCV 2.2 and try the following step by step guide.
http://kaushalsolanki.com/2011/01/compile-and-set-up-opencv-for-visual-studio-2010-with-64-bits-support-ipp-7-0-and-tbb/
I encountered the same error but i finally fixed it
I am using opencv 2.3
what I did was I changed all the additional dependencies
from opencv_core220d.lib to opencv_core231d.lib
we need to change all of the dependencies in the same way
and then i copied all the *.dll files from my bin>>debug folder to
where i had new project that is
helloworld>>helloworld
for example
C:\opencv\build\bin\debug copy all *.dll files to
C:\opencv\Projects\helloworld\helloworld