首页 > 后端开发 > C++ > 正文

如何将 OpenCV Mat 转换为数组或向量?

Barbara Streisand
发布: 2024-10-27 14:12:29
原创
246 人浏览过

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

将 OpenCV Mat 转换为数组/向量

在 OpenCV 中,从 Mat 对象获取数据对于初学者来说可能具有挑战性。本文探讨了将 Mat 转换为数组或向量的过程。

直接转换

如果 Mat 的内存是连续的,则可以直接转换为一维数组:

<code class="cpp">std::vector<uchar> array(mat.rows * mat.cols * mat.channels());
if (mat.isContinuous())
    array = mat.data;</code>
登录后复制

逐行转换

对于非连续 Mats,创建 2D 数组需要逐行访问:

<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>
登录后复制

使用 std::vector 的简化方法

对于 std::vector,转换变得更简单:

<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 数据连续性确保所有数据在内存中是连续的。

  • Imread()、clone() 和构造函数创建的 Mat 始终是连续的。
  • 非连续 Mats 是从现有 Mats 借用数据(例如行/列选择)而产生的。

以上是如何将 OpenCV Mat 转换为数组或向量?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!