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

How to Convert an OpenCV Mat to an Array or Vector?

Barbara Streisand
Release: 2024-10-27 14:12:29
Original
360 people have browsed it

How to Convert an OpenCV Mat to an Array or Vector?

Converting OpenCV Mat to Array/Vector

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>
Copy after login

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>
Copy after login

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>
Copy after login

Data Continuity Considerations

Mat data continuity ensures that all data is contiguous in memory.

  • Imread(), clone(), and constructor-created Mats are always continuous.
  • Non-continuous Mats result from borrowing data from existing Mats (e.g., row/column selections).

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template