Home  >  Article  >  Backend Development  >  How to Convert a Mat Object to an Array or Vector in OpenCV?

How to Convert a Mat Object to an Array or Vector in OpenCV?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 13:48:02193browse

How to Convert a Mat Object to an Array or Vector in OpenCV?

Converting Mat to Array in OpenCV

OpenCV provides various methods for converting between different data structures. In this article, we will focus on the conversion from a Mat object to an array or vector.

Direct Conversion from Mat to Array

For a continuous Mat, where the data is stored contiguously in memory, you can directly access its data as a 1D array:

<code class="cpp">cv::Mat mat;
// ...
std::vector<uchar> array(mat.rows * mat.cols * mat.channels());
if (mat.isContinuous()) {
    array = mat.data;
}</code>

Conversion to 2D Array

For a non-continuous Mat, you can retrieve its data row by row and store it in a 2D array:

<code class="cpp">cv::Mat mat;
// ...
std::vector<std::vector<uchar>> array(mat.rows);
for (int i = 0; i < mat.rows; ++i) {
    array[i] = std::vector<uchar>(mat.cols * mat.channels());
    array[i] = mat.ptr<uchar>(i);
}</code>

Conversion to Vector

If using the C Standard Library's vector, you can employ the following approach:

<code class="cpp">cv::Mat mat;
// ...
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>

Mat Data Continuity

It's worth noting that the continuity of a Mat affects the efficiency of data access. Matrices created by imread(), clone(), or a constructor are typically continuous. Conversely, matrices created from an ROI (region of interest) of a larger Mat may not be continuous.

This code snippet demonstrates the differences in data continuity:

<code class="cpp">cv::Mat big_mat = cv::Mat::zeros(1000, 1000, CV_8UC3);
cv::Mat sub_mat = big_mat(cv::Rect(10, 10, 100, 100));

std::cout << "big_mat is continuous: " << big_mat.isContinuous() << std::endl; // true
std::cout << "sub_mat is continuous: " << sub_mat.isContinuous() << std::endl; // false</code>

The above is the detailed content of How to Convert a Mat Object to an Array or Vector in OpenCV?. 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