C指针的使用(实例)

下面是我遇到的我认为是比较经典的几个指针的例子:

1. yuv的指针

yuv的格式为
Y: size
U: size/4
V: size/4
总的申请内存为 size*3/2

IMAGE *frame = NULL;
frame = (IMAGE *)malloc(sizeof(IMAGE));
frame->h = 240;
frame->w = 240;
frame->pu8D1 = (uchar *)malloc((size * 3 / 2) * sizeof(uchar));
memset(frame->pu8D1, 0, size * sizeof(uchar));
frame->pu8D2 = frame->pu8D1 + size;
frame->pu8D3 = frame->pu8D2 + size / 4;

从视频读图像

FILE* fp=open("test.yuv","rb");
if(NULL==fp)
{
    printf("can not open file");
    return 1;
}
char* buffer = (char*)malloc(size*sizeof(char));
int u32Ret;
for(;;)
{
    // read y
    u32Ret = fread(buffer,size,1,fp);
    if(1!=u32Ret)
    {
        printf("file end");
        break;
     }
     memcpy(frame->pu8D1,buffer,size);

     // read u
     u32Ret = fread(buffer,size/4,1,fp);
    if(1!=u32Ret)
    {
        printf("file end");
        break;
     }
     memcpy(frame->pu8D2,buffer,size/4);

2. 从opencv的Mat读取图像数据

下面代码用一个临时指针,一开始把dst的值赋值给temp, 然后temp++读取数据,这样的好处是不用每次都计算i*w+j

void get_img_data(Mat& src, uchar* dst)
{
    int w=src.cols;
    int h=src.rows;
    uchar* prow;// 行指针
    uchar* temp=; //局部变量,用的是栈内存
    temp=dst;  //把dst指针的位置 给temp
    for(int i=0;i<h;i++)
    {
        prow=src.ptr(i);
        for(int j=0;j<w;j++)
        {
            *temp=*(prow+j);
            temp++;
        }
}

读取图像像素,获取 i=90,j=30这一点的像素
————-C—————-
*(img.ptr(i)+j)
img.data(i*w+j)

———python———–
img[i][j]
img.reshape(w*h)[i*w+j]
另外一个例子,把 w*h的图像信息(四通道 a,r,g,b unsigned char)写入dst中


    int* dst = malloc(sizeof(int)*w*h);
    unsigned char* temp= dst;
    for (int i = 0; i<h; i++) {
        for (int j = 0; j<w; j++) {
            *temp = a[i*w + j];
            temp++;
            *temp = b[i*w + j];
            temp++;
            *temp = g[i*w + j];
            temp++;
            *temp= r[i*w + j];
            t++;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值