opencv cv :: mat分配 [英] opencv cv::mat allocation

查看:368
本文介绍了opencv cv :: mat分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我有一个关于opencv的基本问题.如果我尝试使用cv :: Mat类分配内存,则可以执行以下操作:

Hello I have a basic question about opencv. If I try to allocate memory with the cv::Mat class I could do the following:

cv::Mat sumimg(rows,cols,CV_32F,0);
float* sumimgrowptr = sumimg.ptr<float>(0);

但是随后我得到了一个错误的指针(空).在互联网上有人使用此功能:

but then I get a bad pointer (Null) back. In the internet some person use this:

cv::Mat* ptrsumimg = new cv::Mat(rows,cols,CV_32F,0);
float* sumimgrowptr = ptrsumimg->ptr<float>(0);

在这里我也得到了一个空指针!但是如果我最终做到这一点:

and also here I get a Null pointer back ! but If I finally do this :

            cv::Mat sumimg;
            sumimg.create(rows,cols,CV_32F);
            sumimg.setTo(0);
            float* sumimgrowptr = sumimg.ptr<float>(0);

那一切都很好!所以我想知道我在做什么错了?

then everything is fine ! so I wannted to know what is wrong in what I am doing ?

推荐答案

主要问题在这里

cv::Mat sumimg(rows,cols,CV_32F,0);

OpenCV为矩阵提供了多个构造函数.其中两个声明如下:

OpenCV provides multiple constructors for matrices. Two of them are declares as follows:

cv::Mat(int rows, int cols, int type, SomeType initialValue);

cv::Mat(int rows, int cols, int type, char* preAllocatedPointerToData);

现在,如果您按以下方式声明Mat:

Now, if you declare a Mat as follows:

cv::Mat sumimg(rows,cols,CV_32F,5.0);

您将获得一个浮点数矩阵,使用5.0进行分配和初始化.调用的构造函数是第一个.

you get a matrix of floats, allocated and initialized with 5.0. The constructor called is the first one.

但是这里

cv::Mat sumimg(rows,cols,CV_32F,0);

您发送的是一个0,在C ++中是一个有效的指针地址.因此,编译器为预分配的数据调用构造函数.它不分配任何内容,并且当您要访问其数据指针时,毫无疑问,它是0或NULL.

what you send is a 0, which in C++ is a valid pointer address. So the compiler calls the constructor for the preallocated data. It does not allocate anything, and when you want to access its data pointer, it is, no wonder, 0 or NULL.

一种解决方案是将第四个参数指定为浮点数:

A solution is to specify that the fourth parameter is a float:

cv::Mat sumimg(rows,cols,CV_32F,0.0);

但是最好是通过使用cv :: Scalar()初始化来避免这种情况:

But the best is to avoid such situations, by using a cv::Scalar() to init:

cv::Mat sumimg(rows,cols,CV_32F, cv::Scalar::all(0) );

这篇关于opencv cv :: mat分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆