OpenCV -如何从uint8_t指针创建Mat
OpenCV - how to create Mat from uint8_t pointer
我有以下c++代码:
void foo(const uint8_t* data, int height, int width) {
// need to create a cv::Mat from *data, which is a pointer to grayscale image data
// doesn't work correctly (compiles, but array access on the mat leads to a segmentation fault)
auto img = cv::Mat(height, width, CV_8UC1, &data);
// how can I fix the line above to create a proper cv::Mat?
}
// I'm calling foo like this
// img is a grayscale image
foo(img.ptr<uint8_t>(0), img.cols, img.rows);
有没有人能指出我在创建foo内部矩阵的语法有什么问题?
在本页cv::Mat类参考中,我们可以找到cv::Mat构造函数如下:
///! 2017.10.05 09:31:00 CST
/// cv::Mat public construction
Mat ()
Mat (int rows, int cols, int type)
Mat (Size size, int type)
Mat (int rows, int cols, int type, const Scalar &s)
Mat (Size size, int type, const Scalar &s)
Mat (int ndims, const int *sizes, int type)
Mat (int ndims, const int *sizes, int type, const Scalar &s)
Mat (const Mat &m)
Mat (int rows, int cols, int type, void *data, size_t step=AUTO_STEP)
Mat (Size size, int type, void *data, size_t step=AUTO_STEP)
Mat (int ndims, const int *sizes, int type, void *data, const size_t *steps=0)
Mat (const Mat &m, const Range &rowRange, const Range &colRange=Range::all())
Mat (const Mat &m, const Rect &roi)
Mat (const Mat &m, const Range *ranges)
要从uint8_t pointer
创建cv::Mat
,我们可以使用这两个函数:
Mat (int rows, int cols, int type, void *data, size_t step=AUTO_STEP)
Mat (Size size, int type, void *data, size_t step=AUTO_STEP)
这是我的实验:
///! 2017.10.05 09:40:33 CST
/// convert uint8_t array/pointer to cv::Mat
#include <opencv2/core.hpp>
#include <iostream>
int main(){
uint8_t uarr[] = {1,2,3,4,5,6,7,8,9,10,11,12};
int rows = 2;
int cols = 2;
cv::Size sz(cols,rows);
cv::Mat mat1(sz,CV_8UC3, uarr);
cv::Mat mat2(rows, cols, CV_8UC3, uarr);
std::cout<< "mat1: n"<<mat1 << "nnmat2:n" << mat2 << std::endl;
return 0;
}
结果除外:
mat1:
[ 1, 2, 3, 4, 5, 6;
7, 8, 9, 10, 11, 12]
mat2:
[ 1, 2, 3, 4, 5, 6;
7, 8, 9, 10, 11, 12]
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何在没有数据拷贝的情况下从指针创建一个Eigen VectorXd对象
- 如何从绝对地址的 C 样式指针创建对C++对象的引用
- 不明白使用双指针 (**) 创建 2d 动态数组
- 如何使用指向动态数组的静态指针创建类?
- Opencl:从 c 样式指针创建 UserEvent
- 从 uint16 指针创建垫子
- 如何为指针创建类型定义
- 从原始指针创建const_iterator会在 macOS 上产生编译错误
- 为什么可以使用指针创建新结构,但不能以相同的方式创建双精度?
- 是否可以在 c++17 中为 c 样式指针或原始指针创建弱指针
- 调用虚拟函数而不通过类类型指针创建任何对象
- 如何使用双指针创建指针数组?
- 使用指针创建类成员
- 如何使用成员函数指针创建模板类
- 从现有指针C 创建一个新对象
- 使用指针创建动态数组的问题
- 如何为指向数组的指针创建内存集?
- 使用共享指针创建的链表数组
- 使用C++ 11 中的模板类型的成员函数指针创建方法参数