1. 程式人生 > >opencv中Mat與陣列之間值傳遞的方法

opencv中Mat與陣列之間值傳遞的方法

1.將陣列內容傳遞給Mat

示例程式碼:

unsigned char cbuf[height][width];
cv::Mat img(height, width, CV_8UC1, (unsigned char*)cbuf);
  • 1
  • 2

2.將Mat中的內容傳遞給陣列

如果Mat中的資料是連續的,那麼對於傳遞到一維vector我們可以這樣:

std::vector<uchar> array(mat.rows*mat.cols);
if (mat.isContinuous())
    array = mat.data;
  • 1
  • 2
  • 3
  • 4

同樣的,傳遞到一維陣列我們可以這樣

unsigned char *array=new unsigned char[mat.rows*mat.cols];
if (mat.isContinuous())
    array = mat.data;
  • 1
  • 2
  • 3

對於二維vector的傳值,我們可以這樣處理

uchar **array = new uchar*[mat.rows];
for (int i=0; i<mat.rows; ++i)
    array[i] = new uchar[mat.cols];

for (int i=0
; i<mat.rows; ++i) array[i] = mat.ptr<uchar>(i);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

參考連結 
http://stackoverflow.com/questions/26681713/convert-mat-to-array-vector-in-opencv