Opencv学习----Mat的源码分析(创建和拷贝)

4.2.5 Mat的源码分析

4.2.5.1 创建Mat

以创建如下三个类型的Mat为例:

Mat mat(512, 512, CV_8UC3);//3通道uchar类型
Mat mat(512, 512, CV_8UC4);//4通道uchar类型
Mat mat(512, 512, CV_32FC3);//3通道float类型
//首先,初始化成员变量
//dims:维度;rows:行数;cols:列数;data:数据指针;
//datastart:数据起始指针;dataend:数据结束指针;
Mat::Mat(int _rows, int _cols, int _type)
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), 
    datastart(0), dataend(0), datalimit(0), allocator(0), 
    u(0), size(&rows), step(0)
{
    create(_rows, _cols, _type);
}
void Mat::create(int _rows, int _cols, int _type)
{
    _type &= TYPE_MASK;
    int sz[] = {_rows, _cols};
    create(2, sz, _type);
}
void Mat::create(int d, const int* _sizes, int _type)
{
    //释放内存空间
    release();
    flags = (_type & CV_MAT_TYPE_MASK) | MAGIC_VAL;
    //赋值成员MatSize size和MatStep step;
    setSize(*this, d, _sizes, 0, true);
    if( total() > 0 )
    {
        MatAllocator *a = allocator, *a0 = getDefaultAllocator();
        if(!a)
            a = a0;
	     //分配内存空间
        u = a->allocate(dims, size, _type, 0, step.p, 
        ACCESS_RW, USAGE_DEFAULT);
     }
    //增加引用计数
    addref();
    //完成成员指针赋值
    finalizeHdr(*this);
}
/** 每个通道项的大小,
   0x28442211 = 0010 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */
#define CV_ELEM_SIZE1(type) ((0x28442211 >> CV_MAT_DEPTH(type)*4) & 15)
#define CV_ELEM_SIZE(type) (CV_MAT_CN(type)*CV_ELEM_SIZE1(type))

void setSize(Mat& m, int _dims, const int* _sz, const size_t* _steps, 
bool autoSteps)
{
    //_dims=2
    m.dims = _dims;
    //{ CV_8UC3: esz=3}、{ CV_8UC4: esz=4}、{ CV_32FC3: esz=12}
    size_t esz = CV_ELEM_SIZE(m.flags);
    //{ CV_8UC3: esz1=1}、{ CV_8UC4: esz1=1}、{ CV_32FC3: esz1=4}
    size_t esz1 = CV_ELEM_SIZE1(m.flags);
    size_t total = esz;
    for( int i = _dims-1; i >= 0; i-- )
    {
	  //_sz[] = {_rows, _cols}={512,512}
        int s = _sz[i];
        m.size.p[i] = s;
        m.step.p[i] = total;
        int64 total1 = (int64)total*s;
        total = (size_t)total1;
    }
    //结果: 
    m.size.p[]={512,512}; 
    CV_8UC3:m.step.p[]={1536,3}
    CV_8UC4:m.step.p[]={2048,4}
    CV_32FC3:m.step.p[]={6144,12}
}
UMatData* allocate(int dims, const int* sizes, int type,
void* data0, size_t* step, AccessFlag /*flags*/, 
UMatUsageFlags /*usageFlags*/) const CV_OVERRIDE
{
    //{ CV_8UC3: total =3}、{ CV_8UC4: total =4}、{ CV_32FC3: total =12}
    // sizes[] = {_rows, _cols}={512,512}
    size_t total = CV_ELEM_SIZE(type);
    for( int i = dims-1; i >= 0; i-- )
    {
      step[i] = total;
      total *= sizes[i];
    }
    //CV_8UC3:m.step.p[]={1536,3}、total= 786432=(3*512)*512
    //CV_8UC4:m.step.p[]={2048,4}、total= 786432=(4*512)*512
    //CV_32FC3:m.step.p[]={6144,12}、total= 3145728=(12*512)*512
    //分配空间大小
    uchar* data = data0 ? (uchar*)data0 : (uchar*)fastMalloc(total);
    UMatData* u = new UMatData(this);
    u->data = u->origdata = data;
    u->size = total;
    if(data0)
      u->flags |= UMatData::USER_ALLOCATED;
    return u;
}
//umatdata可以与矩阵数据一起分配,而不是作为单独的对象。因此,它没有构造函数或析构函数;应该使用init()显式初始化它。
struct CV_EXPORTS UMatData
{
enum MemoryFlag { 
        COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2,
        DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8,TEMP_COPIED_UMAT=24,
        USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64,
        ASYNC_CLEANUP=128
    };
    UMatData(const MatAllocator* allocator);
    ~UMatData();
    // 提供对结构的原子访问
    void lock();
    void unlock();
    bool hostCopyObsolete() const;
    bool deviceCopyObsolete() const;
    bool deviceMemMapped() const;
    bool copyOnMap() const;
    bool tempUMat() const;
    bool tempCopiedUMat() const;
    void markHostCopyObsolete(bool flag);
    void markDeviceCopyObsolete(bool flag);
    void markDeviceMemMapped(bool flag);
    const MatAllocator* prevAllocator;
    const MatAllocator* currAllocator;
    int urefcount;
    int refcount;
    uchar* data;
    uchar* origdata;
    size_t size;
    UMatData::MemoryFlag flags;
    void* handle;
    void* userdata;
    int allocatorFlags_;
    int mapcount;
    UMatData* originalUMatData;
};
void Mat::addref()
{
    if( u )
        CV_XADD(&u->refcount, 1);
}
void finalizeHdr(Mat& m)
{
    m.updateContinuityFlag();
    int d = m.dims;
    if( d > 2 )
        m.rows = m.cols = -1;
    if(m.u)
        m.datastart = m.data = m.u->data;
    if( m.data )
    {
        m.datalimit = m.datastart + m.size[0]*m.step[0];
        if( m.size[0] > 0 )
        {
            m.dataend = m.ptr() + m.size[d-1]*m.step[d-1];
            for( int i = 0; i < d-1; i++ )
                m.dataend += (m.size[i] - 1)*m.step[i];
        }
        else
            m.dataend = m.datalimit;
    }
    else
        m.dataend = m.datalimit = 0;
}

4.2.5.2 拷贝Mat

同样以如下三个类型的Mat的拷贝为例:

Mat mat(512, 512, CV_8UC3);//3通道uchar类型
Mat mat(512, 512, CV_8UC4);//4通道uchar类型
Mat mat(512, 512, CV_32FC3);//3通道float类型
Mat dst;
mat.copyTo(dst);
void Mat::copyTo( OutputArray _dst ) const
{
    if( dims <= 2 )
    {
        _dst.create( rows, cols, type() );
        Mat dst = _dst.getMat();
        if( rows > 0 && cols > 0 )
        {
            Mat src = *this;
		    //{ CV_8UC3: elemSize()=3、sz ={786432(512*512*3), 1}}
            //{ CV_8UC4: elemSize()=4、sz ={1048576(512*512*4), 1}}
            //{ CV_32FC3: elemSize()=12、sz ={ 3145728 (512*512*12), 1}}
            Size sz = getContinuousSize2D(src, dst, (int)elemSize());
            const uchar* sptr = src.data;
            uchar* dptr = dst.data;
            //{ CV_8UC3: sz.width =786432}
            //{ CV_8UC4: sz.width =1048576}
            //{ CV_32FC3: sz.width =3145728}
            // sz.height=1
            //{ CV_8UC3: src.step =1536=512*3}
            //{ CV_8UC4: src.step =2048=512*4}
            //{ CV_32FC3: src.step =6144=512*12}
            for (; sz.height--; sptr += src.step, dptr += dst.step)
                memcpy(dptr, sptr, sz.width);
        }
        return;
    }
}

inline MatStep::operator size_t() const
{
    CV_DbgAssert( p == buf );
    //{ CV_8UC3: buf[0]= 1536=512*3}
    //{ CV_8UC4: buf[0]=2048=512*4}
    //{ CV_32FC3: buf[0]=6144=512*12}
    return buf[0];
}
size_t Mat::elemSize() const
{
    //CV_8UC3: step.p[]={1536,3}
    //CV_8UC4: step.p[]={2048,4}
    //CV_32FC3: step.p[]={6144,12}
    //dims=2
    size_t res = dims > 0 ? step.p[dims - 1] : 0;
      return res;
}
Size getContinuousSize2D(Mat& m1, Mat& m2, int widthScale)
{
    const Size sz1 = m1.size();
    if (sz1 != m2.size())  // reshape all matrixes to the same size (#4159)
    {
    ...
    }
    return getContinuousSize_(m1.flags & m2.flags,
                              m1.cols, m1.rows, widthScale);
}
static inline Size getContinuousSize_(int flags, int cols, int rows, int widthScale)
{
    //cols=512、rows=512
    //{ CV_8UC3: widthScale =3}
    //{ CV_8UC4: widthScale =4}
    //{ CV_32FC3: widthScale =12}
    int64 sz = (int64)cols * rows * widthScale;
    //has_int_overflow=false
    //isContiguous=true
    bool has_int_overflow = sz >= INT_MAX;
    bool isContiguous = (flags & Mat::CONTINUOUS_FLAG) != 0;
    return (isContiguous && !has_int_overflow)
         ? Size((int)sz, 1)
         : Size(cols * widthScale, rows);
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要下载OpenCV学习中的运动目标(前景)检测源码,可以按照以下步骤进行。 首先,访问OpenCV的官方网站(https://opencv.org/)或GitHub的OpenCV仓库(https://github.com/opencv/opencv),找到源代码的下载选项。 在官方网站上,可以选择下载最新版本的OpenCV,或者根据特定版本的需求进行选择。在GitHub上,可以浏览仓库的不同分支和版本标签,并选择下载相应的源代码。 一旦选择了合适的源码下载选项,点击下载按钮进行下载。下载完成后,将源代码文件解压缩至本地目录。 接下来,在下载的源代码文件夹中,找到与运动目标检测相关的示例代码或项目。这些示例代码通常位于“samples”或“examples”文件夹中,可以根据名称或说明找到与运动目标检测相关的示例。 打开示例代码文件,使用合适的集成开发环境(IDE)或文本编辑器加载源代码。确保已正确配置编译环境和OpenCV库文件。 阅读示例代码的注释和文档,理解实现运动目标检测的算法和方法。 对于初学者,建议阅读和运行示例代码,以更好地理解和学习运动目标检测的概念和实践。根据需要,可以根据示例代码进行修改和调整,以满足特定的需求。 总之,要下载OpenCV学习中的运动目标(前景)检测源码,首先选择合适的源代码下载选项,然后解压缩源代码文件夹,找到与运动目标检测相关的示例代码或项目,最后阅读和运行示例代码以学习和实践运动目标检测。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dylan55_you

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值