c++ - 图像矩阵转字符串 OpenCV C++

标签 c++ string opencv matrix type-conversion

我必须将 C++ 中的图像矩阵转换为字符串。 我找到了两种方法:

const char *inputD = (const char*)(img.data);
Size imageSiz = img.size();
int w = imageSiz.width;
int h = imageSiz.height;
int ch = img.channels();
_return.append(inputD, w*h*ch);

其中 _return 是:

std::string& _return

而且这个一直在工作。但我还找到了另一种方法:

string matAsStringL (imgL.begin<unsigned char>(), imgL.end<unsigned char>());
_return.push_back(matAsStringL);

当然 _return 是不同的:

std::vector<std::string> & _return

但第二个不适用于彩色图像,而仅适用于灰度图像。为什么?我想了解一下。

我从第二个错误中得到的错误是: 未知函数中断言失败 (elemSize() == sizeof(_Tp))。在mat.hpp中

一个例子是:

img1 = imread(filenameL , 0); //Gray_scale
string matAsStringI(img1.begin<unsigned char>(), img1.end<unsigned char>());
//now in matAsString I have the info I need
cvtColor(img1, coloredImage1, CV_GRAY2RGB);
string matAsStringC(coloredImage1.begin<unsigned char>(), coloredImage1.end<unsigned char>()); //crash here with the assertion error

不适用于 colorImage1,但适用于 img1。如果我更改为 colorImage1 并且使用第一种方法,它工作得很好。

最佳答案

您可以直接在字符串构造函数中使用 mat 迭代器,但您只会获得每个像素的第一个无符号字符,而不是所有数据。

您必须对第一个和第二个解决方案做出妥协,例如

#include <string>
#include <vector>
#include <opencv2/opencv.hpp>

int main()
{
  const char *path = "/home/gerard_gaudeau/Downloads/image.jpg";
  cv::Mat mat = cv::imread(path);
  cv::Size size = mat.size();

  int total = size.width * size.height * mat.channels();
  std::cout << "Mat size = " << total << std::endl;

  std::vector<uchar> data(mat.ptr(), mat.ptr() + total);
  std::string s(data.begin(), data.end());                   
  std::cout << "String size = " << s.length() << std::endl;
  return 0;
}

关于c++ - 图像矩阵转字符串 OpenCV C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23391503/

相关文章:

c# - 自动执行 C++ 库的 C# 包装

c++ - 为什么如果我删除指向基类的指针我会发生内存泄漏?

ios - 将 UITextfield 设置为格式类型

java - 如何在 Java 字符串中插入表情符号?

c++ - OpenCV RGB 比较

c++ - 在灰度 (B/W) 图像上绘制彩色点

C++ 析构函数 - 继承上下文中的显式调用

c++ - 将 std::wstring 拆分为 std::vector

visual-c++ - 如何使用 OpenCV 函数 cvSaveImage() 保存多张不同名称的图像?

c++ - 输出 QProcess readAll 对标签的响应