【问题标题】:How to convert std::string to CV::String in C++?如何在 C++ 中将 std::string 转换为 CV::String?
【发布时间】:2016-07-20 06:52:05
【问题描述】:

我正在调用我自己定义的函数,其中我将 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"); 时,它可以正常工作。不会发生错误。

有人知道怎么改吗?

【问题讨论】:

  • 尝试将c_str()std::string 作为参数传递。
  • 或者你可以投射它docs.opencv.org/3.1.0/d1/d8f/…
  • 当你说“我不能以 cv::String 的形式给出参数”。当您传递参数(并让编译器转换)时会发生什么?你得到什么错误信息。
  • 能否给出相关代码和错误信息?
  • @Mavie 对不起,我也想不通。无论如何,您似乎问错了问题。问题不在于如何将std::string 转换为cv::String,而在于如何将std::string 传递给C 链接函数,以及传递的字符串为何损坏。

标签: .net string opencv c++-cli managed-c++


【解决方案1】:

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

【讨论】:

  • 我已经用我尝试过的代码更新了我的问题。请看
【解决方案2】:

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

imread 在我写一些类似的东西时对我来说很好

std::string filename = "Path/to/img.jpg";
cv::Mat img = cv::imread(filename);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多