Hello I have problem with applying tensorflow model in OpenCV. The code below properly load model, but when calling forward method Assertion error is thrown. Do you have any ideas where is the problem? Or how to debug/find it?
cv::dnn::Net net;
string path;
path = "graph.pb";
net = cv::dnn::readNetFromTensorflow(path);
if (net.empty())
{
std::cerr << "Can't load network by using the given files." << std::endl;
return ;
}
Mat image = imread(imagePath)
Mat inputBlob = cv::dnn::blobFromImage(image, 1.0, Size(512, 512), Scalar(0,0,0), true, false);
int N = inputBlob.size[0], C = inputBlob.size[1], H = inputBlob.size[2], W = inputBlob.size[3]; // [1, 3, 512, 512]
net.setInput(inputBlob); //set the network input
Mat output = net.forward(); // <- throws error
Error:
Debug Assertion Failed!
Program: C:\Workspace\ImageAnalysisPlus\x64\Debug\opencv_world3410d.dll File: C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Tools\MSVC\14.16.27023\include\vector Line: 1789
Expression: back() called on empty vector
For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.
OpenCV version: 4.4.0
Tensorflow model: https://drive.google.com/file/d/1aE0smAw-CyPLch6UY8blK3RreT5RrZfN/view?usp=sharing
Platform: Windows 10, Visual Studio 2017
I tried to load the model in python and OpenCV and it works.
Thank you in advance for any advice.
I have to admit that I didn't try the posted minimal code. It was part of a little bigger code. The minimal code works also on my machine. Knowing that I found out that I was calling the forward method on uninitialized network which caused the error. I initialized local net variable in init method in a class instead of a class attribute.
Related
#include <iostream>
#include <opencv2/highgui.hpp>
using namespace cv;
using namespace std;
// Driver code
int main(int argc, char** argv)
{
//----- COMMAND LINE -----
const String& filename = argv[1];
Mat image = imread(argv[1]);
//----- EXPLICIT WAY -----
//const String& filename = "C:/Users/letto/OneDrive/Things/sonoio.jpg";
//Mat image = imread(filename);
// Error Handling
if (image.empty()) {
cout << "Image File "
<< "Not Found" << endl;
// wait for any key press
cin.get();
return -1;
}
// Show Image inside a window with
// the name provided
imshow("Window Name", image);
// Wait for any keystroke
waitKey(0);
return 0;
}
With the code above I'm trying to open an image.
There are two ways I'm trying to do it:
COMMAND LINE: I pass the image url as a command;
EXPLICIT WAY: I write explicitly the image url.
The second method works perfectly.
With the first method I get this exception:
Exception thrown at 0x00007FFAC1FFF551 (ucrtbased.dll) in OpenImg.exe: 0xC0000005: Access violation reading location 0x0000000000000000.
I'm using Visual Studio Code 2022 so this is the way I'm passing the url through the command line:
Where is the error? Help me find out please, thanks!
You have set - according to the image attached - additional command line arguments to the compiler and not to the app you run.
To add command lines to the app, right click on the project (OpenImg) and choose Debugging -> Command Arguments.
(And, as mentioned by #user4581301, verifying that the argument exists by checking args would've showed that accessing argv[1] would've been out of bounds. Its a good habit to learn.)
I'm now working on feature matching, and I wrote these codes below.
void CLPS::ExtractKeyPoints()
{
vector<DMatch> init_matches;
ULONGLONG timer;
timer = GetTickCount64();
Ptr<BRISK> fd_a = BRISK::create(20);
fd_a->detectAndCompute(S, Mat(), spoints, desc_s, false);
fd_a->detectAndCompute(T, Mat(), tpoints, desc_t, false);
timer = GetTickCount64() - timer;
cout << "Detect and compute: " << timer << " milliseconds complete. Output: " << spoints.size() << " points. \n";
timer = GetTickCount64();
FlannBasedMatcher matcher = FlannBasedMatcher(cv::makePtr<cv::flann::LshIndexParams>(10, 32, 2));
matcher.match(desc_s, desc_t, init_matches);
timer = GetTickCount64() - timer;
cout << "Matching time: " << timer << " milliseconds complete. " << endl;
Point2f spt, tpt;
int num_matches = 0;
vector<DMatch>::iterator iter_matches;
coord_matches.create(1, 3, CV_32FC1);
Mat cm_row;
cm_row.create(1, 3, CV_32FC1);
if (!init_matches.empty())
{
for (iter_matches = init_matches.begin(); iter_matches != init_matches.end(); ++iter_matches)
{
spt = spoints[iter_matches->queryIdx].pt;
tpt = tpoints[iter_matches->trainIdx].pt;
if (std::abs(spt.y - tpt.y) < VERTICAL_EPSILON && tpt.x - spt.x < upperbound && tpt.x - spt.x > lowerbound)
{
num_matches++;
coord_matches.reserve(num_matches);
cm_row.at<float>(0, 0) = spt.x;// 与 CV_32FC1 对应
cm_row.at<float>(0, 1) = spt.y;
cm_row.at<float>(0, 2) = tpt.x - spt.x;
coord_matches.push_back(cm_row);
}
}
cout << coord_matches.rows << " matches found." << endl;
}
else
{
cerr << "No match is found. Validate your source data or report to us if there is a bug. " << endl;
}
}
Then I just call it like this:
CLPS lps;
lps.ExtractKeyPoints();
However, it triggers an exception with following message when this function is returning:
Unhandled exception at 0x00007FFC0797D328 (ucrtbase.dll) in dars_lps.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.
where dars_lps.exe is my application name. Then the program jumps to some destructors in <vector>.
I'm using Visual Studio 2015 on Windows 8.1 Update 1, and my OpenCV version is 3.1. I have confirmed that I'm linking to correct version of library files (i.e. vc14).
I was once working on Visual Studio 2010 on Windows 7 SP1, OpenCV 2.4.9, but it never reported such an exception.
I know this question may be similar to some other questions elsewhere (e.g. this on OpenCV site), occuring when calling different functions, but all of them are staying unsolved. I suspect that the problem lies in BRISK or FlannBasedMatcher, but I can't comment out those code (or this function will be virtually empty, and obviously, no more exceptions).
I also noticed that the problem was rising up after OpenCV 3.0 was released, and most of the similar problems happen in newer versions of Visual Studio or Windows. Both 64-bit and 32-bit platforms have this kind of problems. There does exist a report of such problem in Visual Studio 2015 here, but it was OpenCV 3.0 that is used, when there were no library built for Visual Studio 2015 yet.
Is it still a bug to be fixed or an error of syntax by myself?
I have application made with QTCreator. It uses OpenCV 2.4.11. I have the same application on Visual. Code is the same in both.
OpenCV for Microsoft Visual 2013 was made using this link:
https://www.youtube.com/watch?v=e_TQ9c3n_d8
It is for 2.4.10, but it's the same for 2.4.11.
And I configured QtCreator with this tutorial:
How to link opencv in QtCreator and use Qt library
Now the code:
#include <opencv2\highgui\highgui.hpp>
#include <iostream>
#include <fstream>
#include <opencv2\highgui\highgui.hpp>
#include "opencv2\stitching\stitcher.hpp"
using namespace cv;
using namespace std;
void ReadPhotos();
double begin_t, end_t;
int photo_number = 0;
Mat photos[100];
Mat image;
vector< Mat > ImagesVector;
vector<Mat> roisVector;
int main()
{
cout << "Starting program!" << endl;
ReadPhotos();
Size size(1050, 600);
for (int i = 0; i < photo_number; i++){
//resize(photos[i], photos[i], size);
ImagesVector.push_back(photos[i]);
}
Stitcher stitcher = Stitcher::createDefault(true);
stitcher.setWarper(new SphericalWarper());
stitcher.setFeaturesFinder(new detail::SurfFeaturesFinder(300, 3, 4, 3, 4));
stitcher.setRegistrationResol(0.9);
stitcher.setSeamEstimationResol(0.9);
stitcher.setCompositingResol(1);
stitcher.setPanoConfidenceThresh(1);
stitcher.setWaveCorrection(true);
stitcher.setWaveCorrectKind(detail::WAVE_CORRECT_HORIZ);
stitcher.setFeaturesMatcher(new detail::BestOf2NearestMatcher(false, 0.3));
stitcher.setBundleAdjuster(new detail::BundleAdjusterRay());
Stitcher::Status status = Stitcher::ERR_NEED_MORE_IMGS;
try{
status = stitcher.stitch(ImagesVector, image);
}
catch (cv::Exception e){}
imwrite("panorama.jpg", image);
waitKey(0);
return 0;
}
void ReadPhotos(){
string sourceIN;
string sourcePhoto;
sourceIN = "paths1.txt";
ifstream FileIN(sourceIN);
if (FileIN.is_open())
{
while (getline(FileIN, sourcePhoto)){
photos[photo_number] = imread(sourcePhoto, 1);
photo_number++;
}
}
else{
cout << "Can't find file" << endl;
}
cout << "Number of photos: " << photo_number << endl;
}
Read photos function takes path to images from txt file and load photos.
In visual studio it's working good, I can stitch 3500x2000 resulution images and it gives nice output panorama. In QtCreator I try to stitch the same images and it gives following errors:
OpenCV Error: Insufficient memory (Failed to allocate 290519044 bytes) in OutOfMemoryError, file C:\OpenCV2411\opencv\sources\modules\core\src\alloc.cpp, line 52
terminate called after throwing an instance of 'cv::Exception'
what(): C:\OpenCV2411\opencv\sources\modules\core\src\alloc.cpp:52: error: (-4) Failed to allocate 290519044 bytes in function OutOfMemoryError
Bad alloc - sorry, I can't make this error again so can't copy exactly.
Anyone has any idea why the same code is not working on QTCreator and is working in Visual Studio 2013? Library is the same. One thing I can think of is that I build libraries for QTCreator myself with Cmake. Maybe it has something with this.
i'm starting using opencv with visual studio, these are my sw components and environment:
windows 8.1 (64bit)
visual studio professional 2013
opencv 2.4.9
first of all i've downloaded opencv and extracted all in "C:\OpenCV-2.4.9", then i've created a new environment variable (user variable) OPENCV_DIR with value "C:\OpenCV-2.4.9\opencv\build" and added the string ";%OPENCV_DIR%\x86\vc12\bin" to the existing environment variable Path.
first question: do i should set x64 instead of x86 in the above string value? in general, are all settings right?
then i've created a new win32 console project with visual studio, it creates a function _tmain(int argc, _TCHAR* argv[])inside a .cpp file named .cpp.
second question: what is the reason because i've to use such '_tmain' function instead the classic 'main' function? which is the structure of the calls when i 'run' the project? is that useful? and if i wish use the classic 'main'?
then, i've defined the following code
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 -2;
}
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;
}
when i compile and debug with visual studio everything is ok! but i cannot be able to give the requested parameter to the function... it starts and ends with output code -1 (the first if check).
moreover, if i find the .exe and try to run it using the prompt, an error occurs:
"Impossible to run the program because opencv_core249d.dll is not present...... try to reinstall the program".
it is clear that these are common problems but i'm finding these issue so hard... thanks to all!
I am struggling with an issue regarding running a SQL statement to an Oracle database through C++, using occi. My code is as follows:
#include <iostream>
#include "occi.h"
namespace oc = oracle::occi;
int main() {
std::cout << "Setting up environment...\n";
oc::Environment * env = oc::Environment::createEnvironment();
std::cout << "Setting up connection...\n";
oc::Connection * conn = env->createConnection("user","pass","server");
std::cout << "Creating statement...\n";
//Very simply query...
oc::Statement * stmt = conn->createStatement("SELECT '1' FROM dual");
std::cout << "Executing query...\n";
oc::ResultSet * rs = stmt->executeQuery();
while(rs->next()) {
std::cout << rs->getString(1) << std::endl; //Error is thrown at this line, but after printing since I can see '1' on the console.
}
stmt->closeResultSet(rs);
conn->terminateStatement(stmt);
env->terminateConnection(conn);
oc::Environment::terminateEnvironment(env);
return 0;
}
The error that is shown is:
Unhandled exception at 0x1048ad7a (msvcp100d.dll) in MyDatabaseApp.exe: 0xC0000005: Access violation reading location 0xccccccd0.
My program stops inside 'xstring' at the following line of code:
#if _ITERATOR_DEBUG_LEVEL == 0
....
#else /* _ITERATOR_DEBUG_LEVEL == 0 */
typedef typename _Alloc::template rebind<_Elem>::other _Alty;
_String_val(_Alty _Al = _Alty())
: _Alval(_Al)
{ // construct allocator from _Al
....
}
~_String_val()
{ // destroy the object
typename _Alloc::template rebind<_Container_proxy>::other
_Alproxy(_Alval);
this->_Orphan_all(); //<----------------------Code stops here
_Dest_val(_Alproxy, this->_Myproxy);
_Alproxy.deallocate(this->_Myproxy, 1);
this->_Myproxy = 0;
}
#endif /* _ITERATOR_DEBUG_LEVEL == 0 */
If I change my query to:
oc::Statement * stmt = conn->createStatement("SELECT 1 FROM dual");
and the loop statement to:
std::cout << rs->getInt(1) << std::endl;
It works fine with no errors. I think this is because getting an integer simply returns a primitive, but when an object is being returned it is blowing up (I think on a destructor, but I'm not sure why...)
I have been playing around with this for hours today, and I am pretty stuck.
Some information about my system:
OS - Windows XP
Oracle Version - 10g
IDE - Microsoft Visual Studio 2010 Express C++
My project properties are as follows:
C/C++ - General - Additional Include Directories = C:\oracle\product\10.2.0\client_1\oci\include;%(AdditionalIncludeDirectories)
C/C++ - Code Generation - Multi-threaded Debug DLL (/MDd)
Linker - General - Additional Library Directories = C:\oracle\product\10.2.0\client_1\oci\lib\msvc\vc8;%(AdditionalLibraryDirectories)
Linked - Input - Additional Dependencies = oraocci10.lib;oraocci10d.lib;%(AdditionalDependencies)
I hope I haven't been confusing with too much info... Any help or insight would be great, Thanks in advance!
EDIT If I rewrite my loop, storing the value in a local variable, the error is thrown at the end of the loop:
while(rs->next()) {
std::string s = rs->getString(1); //s is equal to "1" as expected
std::cout << s << std::endl; //This is executed successfully
} //Error is thrown here
Usually such kind of problems come from differences in build environments (IDE) of end user and provider.
Check this.
Related problems:
Unhandled exception at 0x523d14cf (msvcr100d.dll)?
Why does this program crash: passing of std::string between DLLs
First try to use correct lib and dll. If compiled in debug mode then all libs and dlls must be debug. Use VC++ Modules view to be sure that proper DLL loaded.
I was lucky with my application to have all libs compiled for MSVC2010. So I just check debug and release mode DLLs and got working application.
I revisited this issue about a month ago and I found that the MSVC2010 occi library was built for Oracle 11g. We are running Oracle 10g, so I had to use the MSVC2005 library. So I installed the outdated IDE and loaded the Debug library and it worked (for some reason the release version wouldn't work though).
EDIT
For anyone who is having the same problem I was, if downgrading the IDE from MSVC2010 to MSVC2005 with the appropriate libraries doesn't work, you could try upgrading the Oracle client from 10g to 11g and use the MSVC2010 library, as suggested by harvyS. In retrospect this would've probably been the better solution.