Can't display image in Visual Studio 2015 - opencv

Here's my code:
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main()
{
Mat image;
cout << "This image has " << image.rows <<" rows and "<<image.cols<<" columns"<< endl;
image = imread("images.jpg");
if (image.empty()) {
cout << "Image not read properly" << endl;
getchar();
return 0;
}
cout << "The size of the image is " << image.rows << " rows and " << image.cols << " columns." << endl;
cout << "This image has " << image.channels() << " channels." << endl;
namedWindow("Original_Image",CV_WINDOW_AUTOSIZE);
imshow("Original_Image", image);
waitKey(0);
return 0;
}
The window which should display the image is just blank. I'm using Visual Studio 2015, OpenCV 3.2.0.

You might get a blank image if the path of the image is wrong. The blank window is given by the namedWindow statement, which just creates the window. Try giving the full path of the image in imread(eg if your image is saved under Downloads, use the file path as "C:\\Users\\name\\Downloads\\image.jpg"). Be sure to use double back slashes while specifying the file path(forward slash in linux based systems and back slash in windows!!).

Related

Videocapture error: Assertion desc failed at src/libswscale/swscale_internal.h:668 error

Videocapture read give me this error. It started recently when I updated to opencv4. No errors on opencv4 installation. libswscale is up to date, I have libswscale.so.4.8.100.
The code is a simple "open" and "read" video to isolate the problem:
#include<opencv2/core.hpp>
#include<opencv2/videoio.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<string>
#include <iostream>
int main(int argc, char **argv){
cv::VideoCapture video;
std::string filename(argv[1]);
std::cout << "filename " << filename << std::endl;
std::cout << "video.open " << video.open(filename) << std::endl;
union {
char ch[5] = {0};
int i4cc;
} fourcc;
fourcc.i4cc = (int) video.get(cv::CAP_PROP_FOURCC);
std::cout << "Fourcc " << fourcc.ch << std::endl;
cv::Mat frame;
while(true){
std::cout << "video.read " << video.read(frame) << ", Mat.rows " << frame.rows << std::endl;
cv::imshow("imagen", frame);
}
}
The output is this
filename ../Archivos/Vuelta al Lab Uno 720p.MP4
video.open 1
Fourcc avc1
Assertion desc failed at src/libswscale/swscale_internal.h:668
VideoCapture opens the video file, shows fourcc property, and then fails to read first image.
If you ask, video file is fine, I tried with other video files and other video formats, with the same error. These videos play well with ffmpeg.ffplay!
By the way, VideoCapture.read is working fine with webcam. So, it's not clear where the problem is.
Thank you for your time.

video capturing works in the example code, but doesn't in my own project

I built opencv with openni2 using Cmake, and I succeeded to run the example 'openni_capture' which is in OpenCV.sln. It clearly shows the video being captured. I'm using Orbbec Astra camera.
But when I try to make my own project, copy and paste the code, and run it, it says 'can not open a capture object' even if it was successfully built.
The code is like below. The problem is that 'capture.isOpened()' is TRUE in the example project, but it is FALSE in my own project which has exactly same code as the example project.
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
static void colorizeDisparity( const Mat& gray, Mat& rgb, double maxDisp=-1.f, float S=1.f, float V=1.f )
{
.
.
.
}
static float getMaxDisparity( VideoCapture& capture )
{
.
.
.
}
static void printCommandLineParams()
{
cout << "-cd= Colorized disparity? (0 or 1; 1 by default) Ignored if disparity map is not selected to show." << endl;
cout << "-fmd= Fixed max disparity? (0 or 1; 0 by default) Ignored if disparity map is not colorized (-cd 0)." << endl;
cout << "-mode= image mode: resolution and fps, supported three values: 0 - CAP_OPENNI_VGA_30HZ, 1 - CAP_OPENNI_SXGA_15HZ," << endl;
cout << " 2 - CAP_OPENNI_SXGA_30HZ (0 by default). Ignored if rgb image or gray image are not selected to show." << endl;
cout << "-m= Mask to set which output images are need. It is a string of size 5. Each element of this is '0' or '1' and" << endl;
cout << " determine: is depth map, disparity map, valid pixels mask, rgb image, gray image need or not (correspondently), ir image" << endl ;
cout << " By default -m=010100 i.e. disparity map and rgb image will be shown." << endl ;
cout << "-r= Filename of .oni video file. The data will grabbed from it." << endl ;
}
static void parseCommandLine( int argc, char* argv[], bool& isColorizeDisp, bool& isFixedMaxDisp, int& imageMode, bool retrievedImageFlags[],
string& filename, bool& isFileReading )
{
filename.clear();
cv::CommandLineParser parser(argc, argv, "{h help||}{cd|0|}{fmd|0|}{mode|-1|}{m|000100|}{r||}");
if (parser.has("h"))
{
help();
printCommandLineParams();
exit(0);
}
isColorizeDisp = (parser.get<int>("cd") != 0);
isFixedMaxDisp = (parser.get<int>("fmd") != 0);
imageMode = parser.get<int>("mode");
int flags = parser.get<int>("m");
isFileReading = parser.has("r");
if (isFileReading)
filename = parser.get<string>("r");
if (!parser.check())
{
parser.printErrors();
help();
exit(-1);
}
if (flags % 1000000 == 0)
{
cout << "No one output image is selected." << endl;
exit(0);
}
for (int i = 0; i < 6; i++)
{
retrievedImageFlags[5 - i] = (flags % 10 != 0);
flags /= 10;
}
}
int main( int argc, char* argv[] )
{
bool isColorizeDisp, isFixedMaxDisp;
int imageMode;
bool retrievedImageFlags[6];
string filename;
bool isVideoReading;
parseCommandLine( argc, argv, isColorizeDisp, isFixedMaxDisp, imageMode, retrievedImageFlags, filename, isVideoReading );
cout << "Device opening ..." << endl;
VideoCapture capture;
if( isVideoReading )
capture.open( filename );
else
{
capture.open( CAP_OPENNI2 );
if (!capture.isOpened())
{
capture.open(CAP_OPENNI);
}
}
cout << "done." << endl;
if( !capture.isOpened() )
{
cout << "Can not open a capture object." << endl;
return -1;
}
.
.
.
I added to VC++ directory-include directory that
C:\OpenCV_end\Source\opencv-3.4.0\build\install\include ,C:\Program Files\OpenNI2\Include
I added to VC++ directory-library directory that
C:\OpenCV_end\Source\opencv-3.4.0\build\install\x64\vc14\lib ,C:\Program Files\OpenNI2\Lib
I added to Linker-input that
opencv_world340d.lib ,OpenNI2.lib
and I copied the dll files to the folder which contains my project source. opencv_world340d.dll and all the files which are in C:\Program Files\OpenNI2\Redist
but it never wants to work.. Please help me
Thank you.

The result of opencv3.3 dnn module not match the caffe prediction

I used opencv dnn classification, but the result do not match the caffe prediction. What confused me was that some images could get similar result to caffe,a small number of images not.When I changed BGR to RGB, Most of the results ware wrong.
similar result:
different result:
blobFromImage(norm_img, 1.0, cv::Size(64, 64));when used default parameters changed BGR to RGB ,but the result would wrong .so I used like this blobFromImage(norm_img, 1.0, cv::Size(64, 64), cv::Scalar(),false); .most of result would matched caffe prediction,why a small number of images not?
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core/utils/trace.hpp>
using namespace cv;
using namespace cv::dnn;
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
/* Find best class for the blob (i. e. class with maximal probability) */
static void getMaxClass(const Mat &probBlob, int *classId, double *classProb)
{
Mat probMat = probBlob.reshape(1, 1); //reshape the blob to 1x1000 matrix
Point classNumber;
minMaxLoc(probMat, NULL, classProb, NULL, &classNumber);
*classId = classNumber.x;
}
static std::vector<String> readClassNames(const char *filename = "./config/type.txt")
{
std::vector<String> classNames;
std::ifstream fp(filename);
if (!fp.is_open())
{
std::cerr << "File with classes labels not found: " << filename << std::endl;
exit(-1);
}
std::string name;
while (!fp.eof())
{
std::getline(fp, name);
if (name.length())
classNames.push_back(name.substr(name.find(' ') + 1));
}
fp.close();
return classNames;
}
int main(int argc, char **argv)
{
CV_TRACE_FUNCTION();
String modelTxt = "./config/HCCR3755_res20_deploy.prototxt";
String modelBin = "./config/HCCR3755-res20_iter_790000.caffemodel";
String imageFile = "./config/b9.jpg";
Net net = dnn::readNetFromCaffe(modelTxt, modelBin);
if (net.empty())
{
std::cerr << "Can't load network by using the following files: " << std::endl;
std::cerr << "prototxt: " << modelTxt << std::endl;
std::cerr << "caffemodel: " << modelBin << std::endl;
exit(-1);
}
Mat img = imread(imageFile);
FileStorage fs("./config/mean.xml", FileStorage::READ);
Mat _mean;
fs["vocabulary"] >> _mean;
if (img.empty())
{
std::cerr << "Can't read image from the file: " << imageFile << std::endl;
exit(-1);
}
cv::Mat img_resize;
resize(img, img_resize, Size(64, 64));
cv::Mat img_float;
img_resize.convertTo(img_float, CV_32FC3);
cv::Mat norm_img;
cv::subtract(img_float, _mean, norm_img);
Mat inputBlob = blobFromImage(norm_img, 1.0, cv::Size(64, 64), cv::Scalar(),false); //Convert Mat to batch of images
Mat prob;
cv::TickMeter t;
for (int i = 0; i < 1; i++)
{
CV_TRACE_REGION("forward");
//! [Set input blob]
net.setInput(inputBlob, "data"); //set the network input
//! [Set input blob]
t.start();
//! [Make forward pass]
prob = net.forward("prob");
//std::cout << prob << std::endl;//compute output
//! [Make forward pass]
t.stop();
}
int classId;
double classProb;
getMaxClass(prob, &classId, &classProb);//find the best class
//! [Gather output]
//! [Print results]
std::vector<String> classNames = readClassNames();
std::cout << "Best class: #" << classId << " '" << classNames.at(classId) << "'" << std::endl;
std::cout << "Probability: " << classProb * 100 << "%" << std::endl;
//! [Print results]
std::cout << "Time: " << (double)t.getTimeMilli() / t.getCounter() << " ms (average from " << t.getCounter() << " iterations)" << std::endl;
getchar();
return 0;
} //main

How to access each pixel value of RGB image?

I am trying to read RGB image. However, I can only access with Vec3b type, not each channel.
I am sure what is the problem. Would like to help me out of misery?
imgMod = imread("rgb.png");
for (int iter_x = 0; iter_x < imgMod.cols; ++iter_x)
{
for (int iter_y = 0; iter_y < imgMod.rows; ++iter_y)
{
cout << imgMod.at<cv::Vec3b>(iter_y, iter_x) << "\t";
cout << imgMod.at<cv::Vec3b>(iter_y, iter_x)[0] << "\t";
cout << imgMod.at<cv::Vec3b>(iter_y, iter_x)[1] << "\t";
cout << imgMod.at<cv::Vec3b>(iter_y, iter_x)[2] << endl;
}
}
Here is a result for pixel value of RGB image.
[153, 88, 81] X Q
[161, 94, 85] 。 ^ T
...
Your access is fine.
The type returned by the [] operator is char so the value gets printed as a char - a text character. Just cast it to int to see the grey value as an integer:
cout << int(imgMod.at<cv::Vec3b>(iter_y, iter_x)[0]) << "\t";
A (more readable and explicit) C++ way to do it would be this:
static_cast<int>(imgMod.at<cv::Vec3b>(iter_y, iter_x)[0]) << "\t";
Even more cool is this (obscure?) little trick - note the +:
cout << +imgMod.at<cv::Vec3b>(iter_y, iter_x)[0] << "\t";
// ^

OpenCV directshow camera access results in black image unless the camera has been opened previously from other software

An analog framegrabber's image can be read via OpenCV only after the demo-application has opened the grabber, otherwise a black image results.
The following debug code
qDebug() << "Brightness" << cap->get(CV_CAP_PROP_BRIGHTNESS);
qDebug() << "Contrast " << cap->get(CV_CAP_PROP_CONTRAST);
qDebug() << "Saturation" << cap->get(CV_CAP_PROP_SATURATION);
qDebug() << "Hue " << cap->get(CV_CAP_PROP_HUE);
qDebug() << "Gain " << cap->get(CV_CAP_PROP_GAIN);
qDebug() << "Exposure " << cap->get(CV_CAP_PROP_EXPOSURE);
qDebug() << "Width " << cap->get(CV_CAP_PROP_FRAME_WIDTH);
qDebug() << "Height " << cap->get(CV_CAP_PROP_FRAME_HEIGHT);
outputs
Brightness 5000
Contrast 5000
Saturation 4000
Hue 5000
Gain -8.58993e+08
Exposure -1
Width 720
Height 576
Of course these settings seem defective, but they are the same when opening the device successfully after it has been accessed by the grabber's demo application.
I suppose this is a driver issue where certain device settings are required that OpenCV cannot access, including invalid standard settings (gain, exposure). What lower-level methods could be used to find out about / write those settings?
It seems that camera actually did not load yet and OpenCV already tries to take the image.
For me querying couple of more frames usually helps, like this:
CvCapture* capture = cvCaptureFromCAM( CV_CAP_ANY );
if ( capture ) {
IplImage* frame = cvQueryFrame( capture );
for (int i = 0; i < `0; i++)
{
frame = cvQueryFrame(capture);
}
cvSaveImage("mypic.jpg",frame);
cvReleaseCapture( &capture );
}

Resources