OpenCV-如何从uint8_t指针创建Mat [英] OpenCV - how to create Mat from uint8_t pointer
本文介绍了OpenCV-如何从uint8_t指针创建Mat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下C ++代码:
I have the following C++ code:
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内部创建矩阵的语法有什么问题吗?
Could anyone point me on what's wrong with my syntax on creating the matrix inside of foo?
推荐答案
On this page cv::Mat Class Reference , we can find the cv::Mat construction function as follows:
///! 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
,我们可以使用以下两个功能:
To create cv::Mat
from uint8_t pointer
, we can use those two functions:
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)
这是我的实验:
Here is my experiment:
///! 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 << "\n\nmat2:\n" << mat2 << std::endl;
return 0;
}
结果除外:
The result is excepted:
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]
这篇关于OpenCV-如何从uint8_t指针创建Mat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文