gpt4 book ai didi

c++ - GetOpenFileName 对话框和 opencv 的奇怪行为

转载 作者:行者123 更新时间:2023-11-28 02:31:05 25 4
gpt4 key购买 nike

我正在尝试使用打开文件对话框来允许我的程序的用户选择一个图像,然后使用 opencv 对其进行处理。

我有一个功能,我可以在其中打开对话框并尝试加载图像:

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;
}

您在此处看到的代码有效,打开对话框并允许用户选择文件。然后将文件路径转换为字符串(传递到 imread)。当我尝试与图像 src 交互时出现问题。

例如,如果我取消注释“imshow”行,GetOpenFileName 将返回 0 并且对话框甚至不会打开。这种情况经常发生,我实际上无法访问图像,因为我尝试的一切都会导致这种情况发生。

为了使函数工作,它被这样调用:

load_image();

但是如果我尝试分配图像,即:

img = load_image(); 

出现同样的问题。帮助!可能是什么原因造成的?

最佳答案

正如前面评论中提到的,CreateFile 方法锁定图像文件,因此 cv::imread() 无法访问/读取其内容。

尽量避免使用 CreateFile,我认为没有理由在您的代码中使用它,以下代码运行良好:

cv::Mat load_image()
{
cv::Mat outMat;
OPENFILENAME ofn; // common dialog box structure
TCHAR szFile[260]; // buffer for file name

// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFile = szFile;
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)
{
char filepath[260];

wcstombs(filepath, ofn.lpstrFile, 260);
cout << filepath << endl;

outMat = cv::imread(filepath);
}

return outMat;
}

int main()
{
cv::Mat image = load_image();

cv::imshow("image", image);
cv::waitKey(-1);

return 0;
}

关于c++ - GetOpenFileName 对话框和 opencv 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com