0

嗨,我正在尝试为图像比较软件制作 GUI。这个想法是用 OPENFILENAME 选择一张图片,然后用 ofn.lpstrFile 获取它的地址,然后为该图片制作一个直方图。所以我使用:

return(ofn.lpstrFile);

我可以计算地址或将其写入 .xml 文件并且地址是正确的,但是当我尝试制作直方图时,它给了我全零。表现得像地址无效。

有任何想法吗 ?

我的代码:

    string path=browse(); //getting the string from ofn.lpstrFile

    path.c_str();
    replace(path.begin(), path.end(), '\\', '/'); //converting backslash to slash also may be the problem       
    HistCreation(path,root_dir); 

void HistCreation(string path,string root_dir) {

Mat img;
img = imread(path); // here if i manually enter the address everything works fine, if I insert the path then loads empty image

.
.
.

我也试过

char * cstr = new char[path.length() + 1];
    std::strcpy(cstr, path.c_str());

也没有工作

4

1 回答 1

1

std::string返回字符串,这就是你所需要的。这是打开位图文件的示例。

(编辑)

#include <iostream>
#include <string>
#include <windows.h>

std::string browse(HWND hwnd)
{
    std::string path(MAX_PATH, '\0');
    OPENFILENAME ofn = { sizeof(OPENFILENAME) };
    ofn.hwndOwner = hwnd;
    ofn.lpstrFilter = 
        "Image files (*.jpg;*.png;*.bmp)\0*.jpg;*.png;*.bmp\0"
        "All files\0*.*\0";
    ofn.lpstrFile = &path[0];
    ofn.nMaxFile = MAX_PATH;
    ofn.Flags = OFN_FILEMUSTEXIST;
    if (GetOpenFileName(&ofn))
    {
        //string::size() is still MAX_PATH
        //strlen is the actual string size (not including the null-terminator)
        //update size:
        path.resize(strlen(path.c_str()));
    }
    return path;
}

int main()
{
    std::string path = browse(0);
    int len = strlen(path.c_str());
    if (len)
        std::cout << path.c_str() << "\n";
    return 0;
}

请注意,Windows 使用以 NUL 结尾的 C 字符串。它通过在末尾查找零来知道字符串的长度。

std::string::size()并不总是一回事。我们可以调用 resize 来确保它们是同一个东西。


您不需要替换\\/. 如果您的图书馆抱怨\\然后更换如下:

例子:

...
#include <algorithm>
...
std::replace(path.begin(), path.end(), '\\', '/');

用于std::cout检查输出,而不是猜测它是否有效。在 Windows 程序中,您可以使用OutputDebugStringMessageBox查看字符串是什么。

HistCreation(path, root_dir);

我不知道root_dir应该是什么。如果HistCreation失败或它有错误的参数,那么你有一个不同的问题。

于 2016-08-04T20:08:56.360 回答