Convert Mat to Array or Vector in OpenCV
In OpenCV matrix operations, occasionally there's a need to convert Mat to an Array or a Vector. This article provides a comprehensive guide to achieve such conversions, utilizing OpenCV's robust functionality.
Direct Conversion to Array
If the Mat object mat possesses continuous memory, its data can be directly retrieved as a 1D array:
<code class="cpp">std::vector<uchar> array(mat.rows * mat.cols * mat.channels()); if (mat.isContinuous()) array = mat.data;</code>
Conversion to Row-Based Array
In cases where the memory is not continuous, the data can be obtained row by row, resulting in 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>
Alternative Vector Conversion
Using std::vector offers an alternative approach for converting Mat to an array:
<code class="cpp">std::vector<uchar> array; if (mat.isContinuous()) { // array.assign(mat.datastart, mat.dataend); // May cause issues for sub-matrices 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>
Converting to Vectors of Other Types
For OpenCV Mats with other data types, such as CV_32F, the conversion process is similar:
<code class="cpp">std::vector<float> array; if (mat.isContinuous()) { // array.assign((float*)mat.datastart, (float*)mat.dataend); // May cause issues for sub-matrices array.assign((float*)mat.data, (float*)mat.data + mat.total() * mat.channels()); } else { for (int i = 0; i < mat.rows; ++i) { array.insert(array.end(), mat.ptr<float>(i), mat.ptr<float>(i) + mat.cols * mat.channels()); } }</code>
Understanding Mat Data Continuity
It's crucial to comprehend Mat data continuity to effectively perform conversions. Key points to note are:
The above is the detailed content of How to Efficiently Convert OpenCV Mat to an Array or Vector?. For more information, please follow other related articles on the PHP Chinese website!