opencv二进制数据jpg图像到cv::Mat
opencv binary data jpg image to cv::Mat
我想在c++opencv中加载一个来自postgresql数据库的映像。图像扩展名为jpg,以二进制数据(字节类型)的形式存储在库中,多亏了libpqxx,我可以访问它。
问题是我不知道如何将数据转换为cv::Mat实例。对于常规图像,我可以使用imread('myImage.jpg',…),但在这种情况下,我甚至无法在Mat的数据属性中加载数据库图像,因为它是jpeg而不是bmp。
知道吗?有没有什么opencv方法可以让我直接理解二进制数据并将其转换为合适的结构?imdecode()函数似乎用于位图数据。
edit:Berak,使用向量imdecode函数返回null矩阵会发生什么"如果缓冲区太短或包含无效数据,则返回空矩阵/图像。"以下是代码:
pqxx::result r=bdd::requete("SELECT image FROM lrad.img WHERE id=3",1);//returns the bytea image in r[0]["image"]
const char* buffer=r[0]["image"].c_str();
vector<uchar>::size_type size = strlen((const char*)buffer);
vector<uchar> jpgbytes(buffer, buffer+size);
Mat img = imdecode(jpgbytes, CV_LOAD_IMAGE_COLOR);
//jpgbytes.size()=1416562 img.size()=[0 x 0]
我错过了什么?
仍然使用imdecode。它可以处理png、jpg、bmp、ppm、webp、jp2、exr,但不能处理gif。
vector<uchar> jpgbytes; // from your db
Mat img = imdecode(jpgbytes);
(您应该对bmp或任何其他支持的格式执行同样的操作,不要干扰Mat的原始数据指针!)
好的,我有一个将字节数据转换为cv::Mat的过程,这是代码。
inline int dec(uchar x){ //convert uchar to int
if (x>='0'&&x<='9') return (x-'0');
else if (x>='a'&&x<='f') return (x-'a'+10);
else if (x>='A'&&x<='F') return (x-'A'+10);
return 0;
}
cv::Mat bytea2Mat(const pqxx::result::field& f){
const char* buffer=f.c_str();
vector<uchar>::size_type size = strlen((const char*)buffer);
vector<uchar> jpgbytes(size/2-1);
for (size_t i=0; i!=size/2-1;i++) {
jpgbytes[i]=(dec(buffer[2*(i+1)])<<4)+dec(buffer[2*(i+1)+1]);
}
cout <<size/2<<";"<<jpgbytes.size()<<endl;
return imdecode(jpgbytes, CV_LOAD_IMAGE_COLOR);
}
字节输出被加密为char*,看起来像"\x41204230",用于六进制形式的原始输入字符串"a b0"。(根据数据输入,\x可能不存在)要获得原始数据,必须根据两个字符计算原始输入('4','1'=0x41=65)。矢量是字符*大小的一半。
相关文章:
- 将CHW格式的浮点向量转换为cv::Mat
- C++:从GPU内存(cudaMemcpy2D)获取BGR图像(cv::Mat)
- 选择基于另一个垫子的非零像素的cv::Mat的一部分?
- 将 cv::mat 转换为 QImage
- 将 cv::Mat 转换为 std::vector 的通用函数
- 在 QML VideoOutput 中将 cv::mat 显示为 QVideoFrame
- 如何将 cv::Mat 转换为 vtkImageData?
- 如何将 vtkImageData 转换为 cv::Mat?
- 如何总结所有cv::Mat元素
- Qt-工作线程崩溃时将cv::Mat转换为QImage
- 在 cv::Mat 中生成 2D 坐标网格
- 将 cv::Mat 转换为无符号的 int 像素
- OpenCV 分段错误(核心转储)在使用 cv::Mat::at 时
- 如何将多个 cv::Mat 从 c++ dll 传递到 opencvsharp Mat c#?
- 如何在不复制数据的情况下将 cv::Mat 转换为 2d 标准::矢量
- 如何使用 (*mpORBextractorLeft)(im,cv::Mat(),mvKeys,mDescriptors)
- 从数组创建 Mat 时,'cv::Mat' 和 'int' 类型不兼容
- 如何将 cv::mat 对象从 python 模块传递到 c++ 函数并返回返回的 cv::mat 类型为对象?
- 移动语义和 cv::Mat
- OpenCV 错误:断言在 cv::Mat 行 522 中失败