mardi 10 mars 2015

Strange behaviour with GetOpenFileName dialog and opencv

I'm trying to use the open file dialog to allow the user of my program to select an image which will then be processed using opencv. This is my first attempt at any gui or windows programming so bare with me.


I have a function in which i open the dialog and try to load the image:



Mat load_image()
{

OPENFILENAME ofn; // common dialog box structure
TCHAR szFile[260]; // buffer for file name
HWND hwnd; // owner window
HANDLE hf; // file handle

// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = L"All\0*.*\0Text\0*.TXT\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

// Display the Open dialog box.
if (GetOpenFileName(&ofn)==TRUE)
hf = CreateFile(ofn.lpstrFile,
GENERIC_READ,
0,
(LPSECURITY_ATTRIBUTES) NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
(HANDLE) NULL);
char filepath[260];
wcstombs(filepath, ofn.lpstrFile, 260);
cout << filepath << endl;
Mat src = imread(filepath);
//imshow("src", src);
return src;
}


The code you see here works, opens the dialog box and allows the user to choose a file. The filepath is then converted to string (to be passed into imread). The problem occurs when I try to interact with the image src.


For example, if I uncomment the 'imshow' line, GetOpenFileName will return 0 and the dialog box doesnt even open. This happens more than not, I cant actually access the image because everything I try causes this to happen.


In order for the function to work it is called like this:



load_image();


But if I try to assign an image ie:



img = load_image();


the same problem occurs. Help! What could possibly be causing this?


Aucun commentaire:

Enregistrer un commentaire