In OpenCV, obtaining data from a Mat object can be challenging for beginners. This article explores the process of converting a Mat into an array or vector.
Direct Conversion
If the Mat's memory is continuous, direct conversion to a 1D array is possible:
<code class="cpp">std::vector<uchar> array(mat.rows * mat.cols * mat.channels()); if (mat.isContinuous()) array = mat.data;</code>
Row-by-Row Conversion
For non-continuous Mats, row-by-row access is necessary for creating a 2D array:
<code class="cpp">uchar **array = new uchar*[mat.rows]; for (int i = 0; i < mat.rows; ++i) array[i] = new uchar[mat.cols * mat.channels()]; for (int i = 0; i < mat.rows; ++i) array[i] = mat.ptr<uchar>(i);</code>
Simplified Approach with std::vector
For std::vector, the conversion becomes simpler:
<code class="cpp">std::vector<uchar> array; if (mat.isContinuous()) { array.assign(mat.data, mat.data + mat.total()*mat.channels()); } else { for (int i = 0; i < mat.rows; ++i) { array.insert(array.end(), mat.ptr<uchar>(i), mat.ptr<uchar>(i)+mat.cols*mat.channels()); } }</code>
Data Continuity Considerations
Mat data continuity ensures that all data is contiguous in memory.
The above is the detailed content of How to Convert an OpenCV Mat to an Array or Vector?. For more information, please follow other related articles on the PHP Chinese website!