如何在 C++ 中将 std::string 转换为 CV::String?

How to convert std::string to CV::String in C++?

我正在调用我自己定义的函数,在该函数中我将 std::string 作为该函数的参数传递。我还需要输入 cv::Mat cv::imread(const cv::String &filename, int flags=1); 而且我不能给出参数 cv::String。

所以无论如何我都需要将std::string转换为cv::String

更新:

我已将上述函数打包到一个非托管 DLL 中,并从 C# 控制台应用程序调用它,因此它给我错误的内存分配。

我试图在 cv::String 构造函数中转换 std::string 但它没有用。

非托管 C++ 代码(在 Visual studio 2013 年创建的 DLL)

MathFunc.h

#include <stdexcept>
using namespace std;

namespace MathFunc
 { 
   extern "C" { __declspec(dllexport) double DoSomething(std::string imgPath); }

 }

Mathfunc.cpp

#include <iostream>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/core/cvstd.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "MathFuncDll.h"

using namespace std;
using namespace cv;

namespace MathFunc
 {
  double DoSomething(std::string imgPath)
   {
    try{
        cv::Mat image;
        image = cv::imread(imgPath);
    }catch (exception &e){
        cout << "Error Occurred"<< e.what() << endl;
    }
    return 0;
  }
}

这是我在使用时遇到的错误:

OpenCV Error: Insufficient memory (Failed to allocate 1345270332 bytes) in cv::OutOfMemoryError,
file C:\opencv\sources\modules\core\src\alloc.cpp, line 52

所以传递给这个函数的字符串是1345270325 characters long

当我将图像路径指定为 image = cv::imread("C:/path_to_images/input_image.jpg"); 时,它工作正常。没有错误发生。

有谁知道如何纠正这个问题吗?

直接使用 std::string 有什么问题?

imread 当我按照

写一些东西时对我来说很好用
std::string filename = "Path/to/img.jpg";
cv::Mat img = cv::imread(filename);

根据documentcv::String有一个以std::string为参数的构造函数,这意味着std::string可以隐式转换为cv::String .