Home >Backend Development >C++ >How do I efficiently convert an OpenCV Mat object to a C array or vector?
Convert Mat to Array/Vector in OpenCV
In OpenCV, accessing and manipulating image data is crucial for various image processing tasks. One common requirement is the conversion of the Mat object, which represents an image or matrix, to an array or vector.
Conversion to Array
If the Mat object's memory is continuous, meaning all its data is stored consecutively, you can directly obtain a 1D array using the following code:
<code class="cpp">std::vector<uchar> array(mat.rows * mat.cols * mat.channels()); if (mat.isContinuous()) array = mat.data;</code>
where mat is the Mat object, array is the converted array, .rows, .cols, and .channels() represent the image dimensions and number of channels, and .data is a pointer to the image data.
Conversion to Vector
For non-continuous Mats, data needs to be retrieved row by row. Here's an example for converting to a 2D array/vector:
<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>
However, using a std::vector can simplify the conversion:
<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>
Mat Data Continuity
Understanding Mat data continuity is essential for efficient conversion. Here are some key points:
For example, in the following code snippet:
<code class="cpp">cv::Mat image = cv::imread("image.jpg"); // continuous Mat cv::Mat sub_image = image(cv::Rect(100, 100, 100, 100)); // non-continuous Mat since it borrows data from `image`</code>
image is a continuous Mat because it was created using imread(), while sub_image is non-continuous because it references a portion of the image Mat.
The above is the detailed content of How do I efficiently convert an OpenCV Mat object to a C array or vector?. For more information, please follow other related articles on the PHP Chinese website!