1

I was browsing over some code in the OpenCV page when it came to accessing Pixel Data

IplImage* img=cvCreateImage(cvSize(640,480),IPL_DEPTH_32F,3);
CvScalar s;
s=cvGet2D(img,i,j); // get the (i,j) pixel value
printf("B=%f, G=%f, R=%f\n",s.val[0],s.val[1],s.val[2]);
s.val[0]=111;
s.val[1]=111;
s.val[2]=111;
cvSet2D(img,i,j,s); // set the (i,j) pixel value

I had done something similar, but I used the Template Class provided to access pixel data......anyways Im not sure I understand the part s.val[0]=111....etc? if s.val[0] contains the B value, what exactly is s.val[0]=111 doing? is it setting it to black?........I dont understand exactly what it's supposed to be?

Im used to CVscalars and such but I dont understand this format? Specifically what 111 means?

thanks

2 Answers2

5

The cvSet2D(img, i, j, s) functions to not access the (i,j)th pixel. It accesses the (j,i)th pixel. That is because images are stored as a matrix - you need to specify the row first (the Y coordinate) and then the column (the X coordinate).

Instead of using the cvGet/Set functions, did you try using pointers to access data within an image?

Utkarsh Sinha
  • 3,295
  • 4
  • 30
  • 46
  • Good point, but I would claim that i is not necessarily defined as standing for the X-axis anyway.. – ypnos Nov 18 '10 at 22:47
  • Thats the value you're setting at that pixel - you set a triplet (s.val[0], s.val[1], s.val[2]) at point (j, i) – Utkarsh Sinha Nov 21 '10 at 12:32
0

If you want direct access to the pixels, after loading an image you could do something like:

// This example converts a colored image to its grayscale version.
// Let's say that rgb_img is your previously loaded image.
IplImage* gray_frame = 0;
gray_frame = cvCreateImage(cvSize(rgb_img->width, rgb_img->height), rgb_img->depth, rgb_img->nChannels);
if (!gray_frame)
{
  fprintf(stderr, "!!! cvCreateImage failed!\n" );
  return NULL;
}

for (int i = 0; i < rgb_img->width * rgb_img->height * rgb_img->nChannels; i += rgb_img->nChannels)
{
    gray_frame->imageData[i] = (rgb_img->imageData[i] + rgb_img->imageData[i+1] + rgb_img->imageData[i+2])/3;   //B
    gray_frame->imageData[i+1] = (rgb_img->imageData[i] + rgb_img->imageData[i+1] + rgb_img->imageData[i+2])/3; //G
    gray_frame->imageData[i+2] = (rgb_img->imageData[i] + rgb_img->imageData[i+1] + rgb_img->imageData[i+2])/3; //R
}
karlphillip
  • 92,053
  • 36
  • 243
  • 426