OpenCV简化版Mat实现

来源:互联网 发布:spark安装windows 编辑:程序博客网 时间:2024/06/05 23:03

为了理解OpenCV中的Mat结构,自己写了一个简化版本的Mat。
Mat是个结构体,通常用来保存图片信息,比较难理解的一点是图片信息通常是一个矩阵,以数组形式保存,而这个矩阵和Mat的关系是什么呢?
经过深入研究发现,Mat结构体中的data就是指向数组的指针。

#include<stdio.h>#include<stdlib.h>#include<assert.h>#define uchar unsigned chartypedef struct MyMat{    int type;    int step;    union    {        uchar* c;        int* i;    }data;    int height;    int width;}MyMat;//初始化头MyMat* mycreateMatHeader(int width, int height, int type){    MyMat* myheader=(MyMat*) malloc(sizeof(MyMat));    myheader->height = height;    myheader->width = width;    myheader->type = type;    if (0 == type)    {        myheader->step = width*sizeof(uchar);    }else if(1==type){        myheader->step = width*sizeof(int);    }    return myheader;}//为data分配内存void createData(int width,int height,MyMat* mat, int type){    assert(0 == type || 1 == type);    if (0 == type)    {        uchar* p = (uchar*)malloc(sizeof(uchar)*width*height);        mat->data.c = p;    }else if (1 == type)    {        int* p = (int *)malloc(sizeof(int)*width*height);        mat->data.i = p;    }}//myCreateMat包括两个函数,mycreateMatHeader和createDataMyMat* myCreateMat(int width,int height,int type){    //0表示*uchar类型,1表示int*    MyMat* retMat=mycreateMatHeader(width,height,type);    createData(width,height,retMat,type);    return retMat;}MyMat* myInitMatHeader(MyMat* mat, int width, int height, int type, void* data){    mat=myCreateMat(width, height, type);    if (0 == type)    {        mat->data.c =(uchar*) data;    }    else if (1==type)    {            mat->data.i = (int *)data;    }    return mat;}int main(){    MyMat testMat;    uchar vals[4] = { '1', '2','3', '4' };    MyMat* p=myInitMatHeader(&testMat, 2, 2, 0, vals);    printf("width=%d height=%d\n", p->width, p->height);    char* ptr = (char*) p->data.i;    printf("step=%d\n", p->step);    for (int i = 0; i < p->height; i++)    {        char* rptr = (char*) (ptr + i*(p->step));        for (int j = 0; j< p->width; j++)        {            printf("%c\n", *(rptr +j));        }        printf("\n");    }    return 0;}
0 0
原创粉丝点击