Home >Backend Development >C++ >How to Efficiently Convert OpenCV Mat to Array or Vector?

How to Efficiently Convert OpenCV Mat to Array or Vector?

Susan Sarandon
Susan SarandonOriginal
2024-10-29 08:21:30374browse

How to Efficiently Convert OpenCV Mat to Array or Vector?

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:

  • Matrices created by imread(), clone(), or constructors are always continuous.
  • Non-continuous Mats only arise when borrowing data from existing matrices, except when the borrowed data is continuous in the original matrix (e.g., single rows or full-width rows).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn