假设你要访问第K通道,第i行,第j列的像素
一 间接访问:(通用,但效率低,可访问任意格式的图像)
对于单通道字节型图像:
1 IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1); 2 CvScalar s;3 s=cvGet2D(img,i,j); // get the (j,i) pixel value, 注意cvGet2D与cvSet2D中坐标参数的顺序与其它opencv函数坐标参数顺序恰好相反.本函数中i代表y轴,即height;j代表x轴,即weight.也即先cvGet2D的第二个参数i表示行号,第三个参数j表示列号。而元素的坐标值的(j,i) printf("intensity=%f\n",s.val[0]);4 s.val[0]=111; 5 cvSet2D(img,i,j,s); // set the (j,i) pixel value
对于多通道字节型/浮点型图像:
1 IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_32F,3); 2 CvScalar s; 3 s=cvGet2D(img,i,j); // get the (j,i) pixel value 4 printf("B=%f, G=%f, R=%f\n",s.val[0],s.val[1],s.val[2]); 5 s.val[0]=111; 6 s.val[1]=111; 7 s.val[2]=111; 8 cvSet2D(img,i,j,s); // set the (j,i) pixel value
二 直接访问:(效率高,但容易出错)
对于单通道字节型图像:
1 IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1); 2 ((uchar *)(img->imageData + i*img->widthStep))[j]=111;
对于多通道字节型图像:
1 IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3); 2 ((uchar *)(img->imageData + i*img->widthStep))[j*img->nChannels + 0]=111; // B 3 ((uchar *)(img->imageData + i*img->widthStep))[j*img->nChannels + 1]=112; // G 4 ((uchar *)(img->imageData + i*img->widthStep))[j*img->nChannels + 2]=113; // R
对于多通道浮点型图像:
1 IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_32F,3); 2 ((float *)(img->imageData + i*img->widthStep))[j*img->nChannels + 0]=111; // B 3 ((float *)(img->imageData + i*img->widthStep))[j*img->nChannels + 1]=112; // G 4 ((float *)(img->imageData + i*img->widthStep))[j*img->nChannels + 2]=113; // R
三 基于指针的直接访问:(简单高效)
对于单通道字节型图像:
1 IplImage* img = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,1); 2 int height = img->height; 3 int width = img->width; 4 int step = img->widthStep; 5 uchar* data = (uchar *)img->imageData; data[i*step+j] = 111;
对于多通道字节型图像:
1 IplImage* img = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3); 2 int height = img->height; 3 int width = img->width; 4 int step = img->widthStep; 5 int channels = img->nChannels; 6 uchar* data = (uchar *)img->imageData; 7 data[i*step+j*channels+k] = 111;
对于多通道浮点型点型图像(假设图像数据采用4字节(32位)行对齐方式):
1 IplImage* img = cvCreateImage(cvSize(640,480),IPL_DEPTH_32F,3); 2 int height = img->height; 3 int width = img->width; 4 int step = img->widthStep; 5 int channels = img->nChannels; 6 float * data = (float *)img->imageData; 7 data[i*step+j*channels+k] = 111;