下面是我遇到的我认为是比较经典的几个指针的例子:
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++;
}
}