Unable to find the difference in these two OpenCV codes? - c++

I am trying to learn OpenCV and i encounter these two code, the task of both code is same just to show the image but latter one doesn't work. I am using opencv 2.4.6 and visual studio 12
the second doesnt load the image but shows error saying no image found
#include "cv.h"
#include "highgui.h"
int main() // this code works
{
IplImage* newImg;
newImg = cvLoadImage("boxing.jpg", 1);
cvNamedWindow("Window", 1);
cvShowImage("Window", newImg);
cvWaitKey(0);
cvDestroyWindow("Window");
cvReleaseImage(&newImg);
return 0;
}
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
int main() // this code doesn't works
{
Mat image;
image = imread("boxing.jpg");
namedWindow("original");
imshow("original",image);
cvWaitKey(5000);
return 0;
}

Just add
using namespace cv;
after the include statements and before the main function.
Why?
All the OpenCV classes and functions are declared in the namespace cv. Or otherwise, you can also use the scope resolution operator like cv::Mat, cv::imshow etc to access the OpenCV functionality.

Do not mix C functions with C++. While using OpenCv above 2.0 version (C++) you should call:
cv::WaitKey(5000);
as functions and classes starting with "cv" in names are obsolete.

believe it or not, you've got a linker problem.
cvLoadImage() takes a char*, imread() a std::string. if you can't use the latter, it's due to some std/c++ lib wrongly linked.
please check extra carefully, if you're linking release libs against a debug build (or the other way round),
if you accidentally changed the c-runtime (mutithreaded-dll).

Related

imread() still returns empty mat despite correct addressing in openCV 4.0.0

I am newbie to OPENCV.
Now I am trying to display an image using imread(), but imread() doesn't work(keep returning empty mat.) But when I try to draw lines, circles and so on by imread(), it works well.
So I thought there would be something wrong with addressing. And I tried everything I can but it still doesn't work.
And I also have googled a lot of things to solve it, but I can't get any answer to this problem.
What should I do? Is there something wrong I have missed?
I currently use Windows 10, Visual Studio 2017, and openCV 4.0.0 alpha.
Here is my code.
#include <iostream>
#include <opencv2/opencv.hpp>
#ifdef _DEBUG
#pragma comment(lib,"opencv_world400d.lib")
#else
#pragma comment(lib,"opencv_world400.lib")
#endif
using namespace std;
using namespace cv;
int main()
{
Mat image;
image =imread("C:/Users/ymin/source/repos/Project1/Project1/BENZ.bmp",IMREAD_ANYCOLOR);
if (image.empty())
{std::cerr << "Could not open file" << std::endl; return (1);}
imshow("image", image);
waitKey();
return 0;
}
From the OpenCV documentation for imread:
If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix.
This indicates that the file is not there (maybe typo?), you don't have permission to read it, it is in a format not recognized by OpenCV, or it is corrupted.
Make sure the file is where you think it is, and that it is readable, and that OpenCV is compiled to support whatever format the file is in.
(Note that the file extension does not determine its format, you can take a JPEG file and rename it to have a .bmp extension, but it is still a JPEG file.)

OpenCV C++ Xcode on Mac Mojave error NSCameraUsageDescription

I have installed the opencv on MacPro and am trying to write a program which allow me to activate the cam, it is only to test opencv it build successfully, however, the cam is not on and I receive this message
saved enable noise cancellation setting is the same as the default(=1) pentest[30782:364297] [access] This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSCameraUsageDescription key with a string value explaining to the user how the app uses this data
my code is:
#include <iostream>
#include<opencv2/opencv.hpp>
using namespace cv;
int main(int argc, const char * argv[]) {
// insert code here...
VideoCapture cap(0);
while(true){
Mat Webcam;
cap.read(Webcam);
imshow("webcam",Webcam);
}
return 0;
}
I recently posted another answer that addresses this situation:
Put the Info.plist file with the desired NSCameraUsageDescription, NSMicrophoneUsageDescription (or others) with the assembled file from XCode (See screenshots below). For the Release and Debug versions.

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

OpenCV gives an error when trying to get images from an axis camera

I am trying to write a program in OpenCV that just displays the video from an axis camera, which is a type of ip camera. My problem is that OpenCV gives me an error and crashes.
The error is:
OpenCV Error: Bad flag (parameter or structure field) (Unrecognized or unsupported array type) in cvGetMat, file /home/pi/opencv-2.4.5/modules/core/src/array.cpp, line 2482
terminate called after throwing an instance of 'cv::Exception'
what(): /home/pi/opencv-2.4.5/modules/core/src/array.cpp:2482: error: (-206)
Unrecognized or unsupported array type in function cvGetMat
Aborted
My code is:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
Mat img;
namedWindow("IMG", CV_WINDOW_AUTOSIZE);
while(true)
{
img = imread("http://10.17.14.11/jpg/image.jpg");
if(img.empty())cout<<"The image is empty\n";//This cout is printed
imshow("IMG", img);
if(waitkey(1) >=0)break;
}
}
I have tried using a VideoCapture with the address
"http://10.17.14.11/mjpg/video.mjpg"
but I got the same error. I also put both of these URLs into my web browser and they were valid.
Thank you.
EDIT
Could the reason for VideoCapture not working be that I don't have ffmpeg installed?
I guess the function 'imread' only search for files in the current host. You should download the file by other means and then open it using imread.
The error is probably because neither imread or VideoCapture can open remote images. It is easy to check if you try to read a local image instead. At least, I couldn't find anything in the VideoCapture documentation that suggest that remote paths are valid.
If you saw some example, maybe it was using some extended class. It can be very useful to future readers if you find the URL of the example.

I was wondering if you could tell me about the difference between imread and cvLoadImageM

Mat img=imread("box.png",1);
Mat img=cvLoadImage("box.png",1);
When i tried the former one, the project couldn't load the file but when i used the latter one, it did. So.. and box.png was in the project folder. Can you help me what is wrong with my imread? or should i add a directory where box.png is located?
what im trying to make is this code pulling out mser regions from the image. And the error occured running the code when compiler couldn't load the image file, and also even if i had changed imread to cvLoadImageM the code stopped at
ms(box, regions, Mat());
so am i doing something wrong????????here
#include <stdio.h>
#include <iostream>
#include <vector>
//#include <string.h>
#include "opencv\cv.h"
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat box = imread("01a.png",1);
if(box.empty())
{
fprintf(stderr, "Can not load image" );
return -1;
}
MSER ms;
vector<vector<Point>> regions;
ms(box, regions, Mat());
for (int i = 0; i < regions.size(); i++)
{
ellipse(box, fitEllipse(regions[i]), Scalar(255));
}
imshow("mser", box);
waitKey(0);
return 0;
}
I had the same problem yesterday and I found a solution. Make sure the opencv library used matches your build mode (e.g. Release -> cvcore242.lib (dll) Debug -> cvcore242d.lib (or dll)) for each opencv library. Make sure to change your project deps->linker->dependencies to load the correct (Debug or Release) opencv libraries.
An alternative is to switch your build mode Debug <-> Release but I imagine you want to set up each one of the build modes with the proper opencv libraries, for the long run.
imread() is part of the new OpenCV C++ interface and is used with a Mat structure. cvLoadImage() is a C function that returns a IplImage* (pointer to IplImage)
like Cricketer said cvLoadImage() returns a pointer to the image.
Change this in your code
- Mat box = imread("01a.png",1);
+ IplImage* pBox = cvLoadImage("01a.png");
+ Mat box = pBox;
The code worked fine for me both ways putting in the full path to the image
"C:\\Users\\noob\\Pictures\\01a.png"
so, imread failed, and you tried to resolve that using cvLoadImage ? bah, no, don't do that.
please go and check, if you're mixing debug & release code, like *d.libs linked to release build or the other way. it's most likely related to that