getting stared with HDF5 on Visual Studio 2013 with Visual C++ 2013 - visual-c++

I am having a hard time getting an HDF5 example working with Visual Studio 2013 (C++).
The example is at: http://www.hdfgroup.org/ftp/HDF5/examples/misc-examples/stratt.cpp and I've posted the code below for completeness.
My first question is: Will the latest HDF5 (version 1.8.13) work with Visual C++ 2013? The docs only mention 2012 that I can see, but generally I've had no problems using 2013 where 2012 is mentioned.
I tried the example program as both a 32 bit and a 64 bit app. Ultimately, I'm interested in 64 bit. In the project settings for 32 bit, under VC++ settings, I added to the include directories: C:\Program Files (x86)\HDF_Group\HDF5\1.8.13\include
To the library directories, I added: C:\Program Files (x86)\HDF_Group\HDF5\1.8.13\lib
To the Linker->Input, I added: hdf5.lib;hdf5_cpp.lib
When I ran, I (not unexpectedly) got the message, "The program can't start because hdf5.dll is missing from your computer..."
So to the debug directory, I added, hdf5.dll and hdf5_cpp.dll from the directory:
C:\Program Files (x86)\HDF_Group\HDF5\1.8.13\bin
I then get the runtime error:
The application was unable to start correctly (0xc000007b). Click OK to close the application. Any ideas?
Incidentally, when I tried the x64 bit version (using the 64 bit setttings, directories and files), I got slightly different errors. The program runs to the end, but no attribute is written to the console, no file is produced, and I get the dreaded error at the end (after hitting f10 on the last line):
Unhandled exception at 0x000007FEF05E512D (msvcp120d.dll) in HDF5AttributeExample2.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
In both cases (32 and 64 bit) my gut tells me that I have some sort of configuration problem (wrong lib, wrong setup, etc.) I'd really appreciate any help or suggestions folks can offer.
If there is another Visual C++ HDF5 example, by all means please tell me!
Thanks,
Dave
#include <string>
#include <iostream>
#include "H5Cpp.h"
using std::cout;
using std::endl;
using namespace H5;
const H5std_string FILE_NAME("string_test.h5");
const H5std_string DS_NAME("Data Set 1");
const H5std_string ATTR_NAME("String Attribute");
int main(void) {
// Create the named file
H5File file = H5File(FILE_NAME, H5F_ACC_TRUNC);
// Create new dataspace for the dataset
const int rank = 3;
const int dim1 = 2;
const int dim2 = 2;
const int dim3 = 2;
hsize_t dims[rank] = { dim1, dim2, dim3 };
DataSpace dataspace = DataSpace(rank, dims);
// Create new datatype for the dataset
FloatType datatype(PredType::NATIVE_FLOAT);
// Create the dataset
DataSet dataset = file.createDataSet(DS_NAME, datatype, dataspace);
// Set up write buffer 'matrix'
int q, r, s;
float value;
float matrix[dim1][dim2][dim3];
for (q = 0; q < dim1; q++)
for (r = 0; r < dim2; r++)
for (s = 0; s < dim3; s++)
{
value = 1.111 + (q * r * s);
matrix[q][r][s] = value;
}
// Write data to the dataset
dataset.write(matrix, datatype);
// Create new dataspace for attribute
DataSpace attr_dataspace = DataSpace(H5S_SCALAR);
// Create new string datatype for attribute
StrType strdatatype(PredType::C_S1, 256); // of length 256 characters
// Set up write buffer for attribute
const H5std_string strwritebuf("This attribute is of type StrType");
// Create attribute and write to it
Attribute myatt_in = dataset.createAttribute(ATTR_NAME, strdatatype, attr_dataspace);
myatt_in.write(strdatatype, strwritebuf);
// Set up read buffer for attribute
H5std_string strreadbuf("");
// Open attribute and read its contents
Attribute myatt_out = dataset.openAttribute(ATTR_NAME);
myatt_out.read(strdatatype, strreadbuf);
// Display attribute contents
cout << "Attribute contents: " << strreadbuf << endl;
return 0;
}

The runtime error that you are getting arises from the fact that you are using libraries that were compiled with VS2012.
From the HDF Group website on VisualStudio and CMake:
First, make sure you use the same version of Visual Studio that was used to create the pre-built binaries. This is required to avoid runtime errors.
I suggest that you try by yourself to build the source code on VS2013 using CMake.
Ok, after having tried myself to compile it for the VS2013 Ultimate I managed to get it working with both 32 bit and 64 bit support.
Download the source code and unzip it. Let's assume the directory name is "source".
Download CMake and open the GUI, choose the source location and choose a "build" location.
Click Configure and select the version from visual studio you are using.
The configuration options will appear in red on CMake. Choose whatever you need.
Click on generate.
Go to the "build" folder and open the generated MSVS solution. Build the solution.
In the same build folder run the command
"cpack -C {Debug | Release} ---config C:\...\"build"\CPackConfig.cmake. This will create an installer for the files.
Run this installer.
Create an empty project in MSVS. Go to Project Configuration Properties. Then select C/C++ -> General -> Additional Include Directories and insert C:\Program Files (x86)\HDF_Group\HDF5\1.8.13\include. Change this path accordingly. If you are using a x64 version, you will need to change the platform on top of this window to x64. If it doesn't exist, click on Configuration Manager and from the Active Solution platform drop down menu choose New. Add the x64 option.
Now go to Linker - > General -> Additional Library Directories: Add C:\Program Files (x86)\HDF_Group\HDF5\1.8.13\lib. Change this also accordingly. Note that if you built the binaries for x64 they will be installed at C:\Program Files\HDF_Group\HDF5\1.8.13\.
Got to Linker -> Input -> Additional Dependencies. Add libhdf5_D.lib and libhdf5_cpp_D.lib if you built it as debug, otherwise (I believe) use hdf5.lib and hdf5_cpp.lib.
Good Luck!

Doesn't look like too many people are interested in HDF5 with Visual C++ judging by the number of views. Perhaps that should be a warning to me! In any case, for posterity I offer the following answers to my original question.
First of all, one needs to be very careful that the path variable is correct in environments settings AND that it is set up correctly for 32 bit or 64 bit depending on which you want.
Instead of:
C:\Program Files (x86)\HDF_Group\HDF5\1.8.13\bin
I have:
C:\Program Files (x86)\HDF Group\HDF5\1.8.13\bin (notice missing underscore)
Additionally, one has to pay attention as to where you want 32 bit (use Program File (x86)) or 64 bit (use Program Files). If anyone knows of an easier way to run 32 bit and 64 bit programs on the same machine that use HDf5, please let me know.
The other major problem was with the example code itself. In it's original form, it did not work. After much trial and error, I tracked the problem down to the use of H5std_string. When I replaced these with char [], everything worked. As an example, instead of using:
const H5std_string FILE_NAME("string_test.h5");
I used:
char fileName[128] = "string_test.h5";
and used H5File constructor as so:
H5File file = H5File(fileName, H5F_ACC_TRUNC);
It's annoying that I didn't get a compile time error. The constructor claims to take std::string (which is what H5std_string is) in the constructor for H5File. Quite possibly, there is some Visual Studio setting somewhere that makes things the original code work. I'm not knowledgeable enough about Visual C++ to know.
Anyhow good luck all.
Dave

Related

Visual C++ Release build - is string getting corrupted when passed across DLL because compiled with different runtime version?

After building in Release mode, I am seeing exceptions which didn't occur in Debug mode. When debugging the release build, it looks like string references are not being passed correctly from the EXE (our application) to the DLL which is receiving the string reference.
Our EXE code looks like this:
string contents = "handle_message(): received=" + msg->encode();
LOG4CXX_DEBUG(logger, contents);
The LOG4CXX_DEBUG is going to log4cxx.dll, whose code looks like this:
CharMessageBuffer& CharMessageBuffer::operator<<(const std::basic_string<char>& msg) {
if (stream == 0) {
buf.append(msg);
} else {
*stream << msg;
}
return *this;
}
Looking at the Call Stack in the debugger, when I navigate down to the frame which has our source, I can see that contents is a valid string with size=583, capacity=838.
In the frame inside the log4cxx.dll (the next frame above in the stack) the string reference shows size=838, capacity=363113231 (and the values are all garbage).
Both our app and log4cxx.dll were compiled on the same machine, using the same runtime settings (/MD), but different versions of Visual Studio. The log4cxx dll was compiled using Visual Studio 2008 and our application was compiled using Visual Studio 2010. Running dumpbin on the 2 objects shows:
Our App (EXE)
MSVCP100.dll
MSVCR100.dll
log4cxx.dll (DLL)
MSVCP90.dll
MSVCR90.dll
Is this problem due to the fact that they are using different runtime versions?
If you pass non-POD (plain old datatypes) between DLL/EXE boundaries (like STL string or CRT FILE pointers) you must use the same shared CRT.
In your case, you must recompile all DLLs/LIBs with the same compiler!
See also: I can pass std::string for a Dll and what i can do with DLL´s?
The implicit question is:"Is there a way to pass data, hopefully using string and other STL containers, to DLLs of another version of visual studio either previous or later than the one that I'm using?".
Aside from using POD, there are probably three approaches: shared memory, sockets( to local host ) and MSMQ. All of these methods require additional extensive programming, but the deeper answer is found in how the interface is changing the input parameter.
I have found a possible solution to the string passing problem on the internet. It removes one layer of corruption; cast a pointer to the container to a uint and pass the uint. Dereference the uint to the pointer and the object is revealed. Beware, auto_ptrs are usually deleted in this process, so don't use them. If the passed object is still offset incorrectly( this happened to me with VS08 passing to a VS13 ), then pass the c_str() of the string instead. It's certainly inelegant, but we need to know all the alternatives. See "HowTo: Export C++ classes from a DLL" in Code Project( Nov 22, 2012 ).

Setting VIPS library for visual studio 2012

I am trying libvips for visual studio 2012, starting with a simple example at
http://www.vips.ecs.soton.ac.uk/supported/current/doc/html/vipsmanual/vipsmanualse1.html#x6-60001.1.1
#include <iostream>
#include <vips/vips>
int
main (int argc, char ⋆⋆argv)
{
if (argc != 3)
{
std::cerr << "usage: " << argv[0] << " infile outfile\n";
return (1);
}
try
{
vips::VImage fred (argv[1]);
fred.invert ().write (argv[2]);
}
catch (vips::VError e)
{
e.perror (argv[0]);
}
return (0);
}
What I did was:
Download and extract libvips at http://www.vips.ecs.soton.ac.uk/supported/7.34/win32/
Add to VC++ Directories->Include directories as vips-dev-7.34.1\include (vips-dev-7.34.1 is the extracted folder)
Add to VC++ Directories->Library directories as vips-dev-7.34.1\lib
Add a system path entry as vips-dev-7.34.1\bin
Basically because there are not much guide on using libvips with visual studio, so I applied the procedure that I used for OpenCV. The guide only say "All you need to do is include . This will get all of the include you need". Aparrently there are much more than that.
Upon building, the first error is "Unable to find header file "glib-object.h". Essentially, vips/vips call glib-objects "include which lies inside a subfolder of include \include\glib-2.0\glib-objects.h. I searched for a way to make VS search for all subfolders within the main include folder, it seems that such "recursive search" is not possible in VS. One has to point exactly to the folder containing header file and I may need to add all of the subfolders manually. So I tried adding vips-dev-7.34.1\include\glib-2.0 to VC++ Directories->Include directories. But then glib-objects.h calls for another glibconfig.h which is nowhere to be found within the include folder and subfolders.
Have someone sucessfully make libvips work with VS? Can you give me some advices if I miss something.
I'm the libvips maintainer. Sorry, it's very difficult to use the pre-built libvips binaries with VS, for various reasons (see below). I think your options are to use mingw instead, to cross-compile from linux (this is what I do), or to rebuild libvips yourself from source using VS (perhaps a week's work for an experienced dev?). There are some notes on the vips website about this issue.
The libvips.dll on the website has been cross-compiled from linux using mingw. It's set up for a linux-style build system with pkg-config, so you will have a lot of compiler flags to figure out in VS, and it's built against msvcrt.dll, the Windows C runtime, rather than msvcrtXX.dll, the VS runtime, so you will have endless annoying compatibility problems unless you also build against the Windows runtime.
Unfortunately VS no longer supports building against the Windows runtime. They have an internal tool which does support this mode, but it's not publicly available. I read somewhere you can coax the DDK compiler into doing this, but it's also not supported.
CoApp is an interesting project (partly supported by Microsoft) that is attempting to make building software on Windows less painful, but it's still in beta. You could maybe ask if they have a libvips packaged up for VS, or are considering making one.

How to Generate a text file in WinCE 6.0 application using MFC?

I am trying to create a text file through my code. The file is created but its extension is different(not .txt). Then on searching i came to know that this can be because of MFC runtimes.
I searched for the MFC Runtimes in my C:\program Files\Windows CE tools\SDK but i am not able to find the MFC folder there. What should i do? from where should i include MFC Runtimes?
here's the text file generation code which i am using:
void CFormRight::OnBnClickedButtonTextfile()
{
CFile File;
char cFileAddr[100] = {"My Device\\Label.txt"};
File.Open((LPCTSTR)cFileAddr, CFile::modeCreate | CFile::typeBinary |CFile::modeWrite | CFile::shareDenyNone);
File.Write("Hello World", 15);
File.Close();
}
If you're just looking for the DLLs, try looking on your development machine here:
%PROGRAM_FILES%\Microsoft Visual Studio 9.0\VC\ce\dll
That gets you the actual libraries. Including them in the OS image can be done a variety of ways. Typically you'd add them to your platform or project BIB file.
Even with all of that, though, I don't think it's going to solve your problem of a file extension. If you're creating a file and it shows up, just without an extension, it has nothing to do with MFC being there or not, it has to do with either your code, or the way you're determining there is no extension (is "hide file extensions" turned on in Explorer?). To solve that problem, we'd need to see code.
** Edit **
Windows CE is heavily biased toward Unicode. Nearly all Win32 APIs only have the Unicode variant exposed, therefore your code should also lean toward Unicode, meaning string you pass around that will end up at API calls should be Unicode.
Second, you should not ignore the compiler when it complains. The cast you have in there I bet was due to a compiler complaint, and it's just incorrect. If your original code was this (note the lack of cast on the first parameter):
File.Open(cFileAddr, CFile::modeCreate | CFile::typeBinary |
CFile::modeWrite | CFile::shareDenyNone);
Then you would get a compiler error:
error C2664: 'CFile::Open' : cannot convert parameter 1 from 'char [100]' to 'LPCTSTR'
That's because under Windows CE, Open is looking for a wide (Unicode) string. You have an ANSI string. You cannot convert from ANSI to Unicode through a simple direct cast like you did. Yes, the compiler will quit complaining, but it gives bad behavior. You can cast an int to a char[] too, but that doesn't mean it will work for the API.
So change your code to use wide strings and all will work:
CFile File;
CFileException ex;
wchar_t cFileAddr[100] = TEXT("My Device\\Label.txt");
if(!File.Open(cFileAddr, CFile::modeCreate | CFile::typeBinary |
CFile::modeWrite | CFile::shareDenyNone))
{
wchar_t error[1024];
ex.GetErrorMessage(error, 1024);
cout << "Error opening file: ";
cout << error;
return;
}
File.Write("ID Technologies", 15);
File.Close();
Note the use of wchar_t, the initialization using the TEXT macro, and the lack of the cast in the Open call.
EDIT 2
I added error handling in the code above, but really you should learn to read the documentation and how to debug. This is a pretty basic usage scenario, and knowing how to look for errors is critical.

How to get .exe file version number from file path

I am using .Net 3.5/4.0 with code in C#.
I am trying to get a version number of an exe file on my C: drive.
For example path is: c:\Program\demo.exe. If the version number of demo.exe is 1.0.
How can i use this path to grab version number?.
You can use FileVersionInfo.FileVersion to fetch this from a path.
var versionInfo = FileVersionInfo.GetVersionInfo(pathToExe);
string version = versionInfo.FileVersion; // Will typically return "1.0.0.0" in your case
Updated and modernized 2018 (e.g. string interpolation of C#6):
The accepted answer is partly not correct (ProductVersion is not typically returning three-part version) and a bit misleading:
Here is a more complete answer. To get the main text not too lengthy I splitted it in a short(er) summary which may be "enough" for a lot of people. You are not obliged to read the detailed second part, so please no tl;dr :-)
Short summary:
There are different versions (assembly version, file version, product version) of each file, but normally you will have them all equal to not get "version hell" already on file level (it will come early enough).
The file version (which is visible in Explorer and used in setups/installations) is, what I would name the most important to bother.
To achieve this, simply comment out fileversion in AssemblyInfo.cs file as below. This assures that the three possible different versions of one file are the same!
[assembly: AssemblyVersion("1.1.2.")]
//[assembly: AssemblyFileVersion("1.1.2.")]
E.g. for Semantic versioning you want to get only 3 version parts out of possible 4 :
Having an automatic build counting for every Visual Studio build is useful. But this build counting is not always useful to tell your customers, internal or external. So for mentioning the file version to windows, in title dialogs, I would advice to show only three parts v1.2.3 (and of course with semantic versioning):
using System.Diagnostics;
...
var versInfo= FileVersionInfo.GetVersionInfo(pathToVersionedFile);
string fileVersionFull = versInfo.FileVersion; // No difference here for versinfo.ProductVersion if recommendation in AssemblyInfo.cs is followed
string fileVersionSemantic = $"V{versInfo.FileMajorPart}.{versInfo.FileMinorPart}.{versInfo.FileBuildPart}";
string fileVersionFull2 = $"V{versInfo.FileMajorPart}.{versInfo.FileMinorPart}.{versInfo.FileBuildPart}.{versInfo.FilePrivatePart}";
FileVersionFull2 is just showing how to handle all 4 parts, except the "V" it contains the same as FileVersionFull .
Details:
First is a cheat sheet about how to get and set the three versions:
File version: [assembly: AssemblyFileVersion(..)] => System.Diagnostics.FileVersionInfo.FileVersion
Product version: [assembly: AssemblyInformationalVersion(..)] => System.Diagnostics.FileVersionInfo.ProductVersion
Assembly version: [assembly: AssemblyVersion(..)] => System.Reflection.Assembly.Version
Especially the defaulting may be confusing. Recommended SO link to understand details: FileVersionInfo and AssemblyInfo
EntryAssembly vs. ExecutingAssembly
For fully considering every case for getting the version of the running app, search elsewhere for more details, e.g. here:
Which is better for getting assembly location , GetAssembly().Location or GetExecutingAssembly().Location
Especially, there can be confusion, if EntryAssembly or ExecutingAssembly should be used. They both have advantages and caveats.
If you have the following code not in the same assembly as the .exe, e.g. in a helper assembly, things get more complicated. Usually you would use EntryAssembly then, to get the version of the .exe.
But: For unit tests in Visual Studio to test routines in a parallel .exe project, GetEntryAssembly() doesn´t work (my env: NUnit, VS2017). But GetExecutingAssembly() doesn´t crash at least, only during unit test you get the assembly version of the test project. Fine enough for me.There may be situations which are not as simple.
If wanted, you can omit the declaration as static making it really possible to get versions of several different assemblies in one program.
public static class AppInfo
{
public static string FullAssemblyName { get; }
..
static AppInfo()
{
Assembly thisAssembly = null;
try
{
thisAssembly = Assembly.GetEntryAssembly();
}
finally
{
if (thisAssembly is null)
thisAssembly = Assembly.GetExecutingAssembly();
}
FullAssemblyName = thisAssembly.Location;
var versInfo = FileVersionInfo.GetVersionInfo(FullAssemblyName);
..
}
}
Product version vs. file version:
ProductVersion of a file is shown in Windows Explorer too. I would recommend to maximally differentiate ProductVersion and FileVersion in the most "customer-visible" file (mostly the main .exe of application). But it could be of course a choice to differentiate for every file of the "main" app and let them all have them all the "marketing" ProductVersion which is seen by customer.
But experience shows that it is neither necessary nor cheap to try to synchronize technical versions and marketing versions too much. Confusion doesn´t decrease really, costs increase. So the solution described in the first part here should do it mostly.
History: Assembly version vs. file version:
One reason for having different versions is also that one .NET assembly can originally consist of several files (modules)- theoretically. This is not used by Visual Studio and very seldom used elsewhere. This maybe one historical reason of giving the possibility to differentiate these two versions.
Technically the assembly version is relevant for .NET related versioning as GAC and Side-by-side versions, the file version is more relevant for classic setups, e.g. overwriting during updates or for shared files.
In the accepted answer a reference is made to "pathToExe".
This path can be retrieved and used as follows:
var assembly = Assembly.GetExecutingAssembly();
var fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
var version = fvi.FileVersion; // or fvi.ProductVersion
Hope this saves someone from doing some unnecessary extra steps.
Where Program is your class name:
Console.WriteLine("Version = " + typeof(Program).Assembly.GetName().Version.ToString()) ;
I'm not sure if this is what you are looking for, but:
http://www.daniweb.com/software-development/csharp/threads/276174/c-code-to-get-dll-version
It says,
// Get the file version info for the notepad.
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\notepad.exe");
// Print the file name and version number.
Console.WriteLine("File: " + myFileVersionInfo.FileDescription + '\n' + "Version number: " + myFileVersionInfo.FileVersion);
Use this, it works:
using System.Reflection;
string v = AssemblyName.GetAssemblyName("Path/filename.exe").Version.ToString();
This works good and returns the version provided in AssemblyVersion:
using System.Reflection;
infoFileVersionInfo versInfo = FileVersionInfo.GetVersionInfo("path.exe");
string version = $"v{versInfo.FileMajorPart}.{versInfo.FileMinorPart}.{versInfo.FileBuildPart}";
Solution 1
Dim fileVer As FileVersionInfo = FileVersionInfo.GetVersionInfo(Environment.CurrentDirectory + "\yourExe.exe")
yourLabel.Text = fileVer.FileVersion
Solution 2
Get File Version Number
yourLabel.Text = Application.ProductVersion
Both solutions will give 1.0.0.0

OpenCV 2.0 C++ API using imshow: returns unhandled exception and "bad-flag"

I'm trying to use the new OpenCV 2.0 API in MS Visual C++ 2008 and wrote this simple program:
cv::Mat img1 = cv::imread("image.jpg",1);
cv::namedWindow("My Window", CV_WINDOW_AUTOSIZE);
cv::imshow("My Window", img1);
Visual Studio returnes an unhandled exception and the Console returns:
OpenCV Error: bad flag (parameter or structure field)
(Unrecognized or unsupported array type) in unknown function,
file ..\..\..\..\ocv\opencv\src\cxcore\cxarray.cpp, line 2376
The image is not displayed. Furthermore the window "My Window" has a strange caption: "ÌÌÌÌMy Window", which is not dependent on the name.
The "old" C API using commands like cvLoadImage, cvNamedWindow or cvShowImage works without any problem for the same image file. I tried a lot of different stuff without success.
I appreciate any help here.
Konrad
As I just commented, imread isn't working for me either. A little googling shows other people having the same problem; I guess it's a bug in the library code. For now, here's a hacky workaround:
IplImage* img = cvLoadImage("lena.jpg");
cv::Mat lena(img);
cvReleaseImage(&img);
This way, you can at least use the C++ API for the rest of your stuff.
There's help for this issue.
The solution is, that the usual proposed opencv library files in the linker are not working properly. Instead try to use the debug library files by this:
In Visual C++:
go to Project->Properties (or Alt-F7)
Configuration Properties->Linker->Input->Additional Dependencies
replace the usual
" cv210.lib cxcore210.lib highgui210.lib" by
" cv210d.lib cxcore210d.lib highgui210d.lib" - which are the debugging libraries.
The OpenCv 2.0 API commands should work now.
I had the same problem described above which turns out to be caused by the settings of the linker.
I found the answer in another thread,
OpenCV 2.3 and Visual Studio 2010.
To repeat it here:
Properties of your project (right click on it)
C/C++
General
include directory add the < your directory >\OpenCV2.3\include\opencv2, < your directory >\OpenCV2.3\include\opencv and < your directory >\OpenCV2.3\include
Linker
General
List item
Input
Add all the libs like opencv_core230d.lib opencv_highgui230d.lib and so on...
Once I've done the above, I can run imshow and imread + all other cpp functions seamlessly! OP's problem has probably already been resolved, but hopefully this will be useful to other people who are led here looking for the same solution.
Are you sure you added the whole path starting from /home/.... I had the same problem as you but when I added the whole path, things work out pretty well. The whole path had to be added despite the fact the path exists in the include files.
imread in openCV unlike Matlab does not return an error when file/folder is not found - instead it returns a null matrix, which in turn is reflected as an error during imshow.
Also, imread does not look for image files in the included folders or the workspace. So, specify the entire path whenever possible.
Please take a note of this for future references.
Firstly, you'd better compile your own version OpenCV.
I had the same error with the build (I got from Sourceforge), and solved by compiling my own version in debug and release versions.
And make sure you change the original system env variable PATH to the new build folder build/bin, then you could build and run the imshow() in Debug mode.
I believe this might be related to unicode.
Try the macro _TEXT()
For example:
cv::Mat img1 = cv::imread(_TEXT("image.jpg"),1);
Unicode in Visual C++ 2

Resources