Converting OpenCV Mat to Array/Vector
Problem:
For beginners in OpenCV, finding suitable functions to convert Mat to Array can be challenging. Existing methods like .ptr and .at may not provide the desired data format.
Answer:
For continuous Mats (where all data is stored consecutively), the 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>
For non-continuous Mats, the data needs to be extracted 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>
Update:
For increased simplicity, using std::vector is recommended:
<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>
For data types other than CV_8UC1 (e.g., CV_32F), use the appropriate data type in the vector definition.
Update 2:
Regarding Mat data continuity:
The above is the detailed content of How to Efficiently Convert OpenCV Mat to Array or Vector?. For more information, please follow other related articles on the PHP Chinese website!