Ask Your Question
0

Reading pixel values from a frame of a video

asked 2012-08-30 14:01:48 -0500

Himanshu gravatar image

Hi,

Is this the right way of reading pixel values from a frame of video?:

IplImage* bgr_frame = cvQueryFrame( capture );
int width, height, nchannels, step;
int i, j, r_ch, b_ch, g_ch;

width = bgr_frame->width;
height = bgr_frame->height;
nchannels = bgr_frame->nChannels;
step = bgr_frame->widthStep;
uchar *data = ( uchar* )bgr_frame->imageData;

for(i = 0 ; i < height ; i++) 
{
  for( j = 0 ; j < width ; j++)
  {
    b_ch = ((uchar *)(bgr_frame->imageData + i*bgr_frame->widthStep))[j*bgr_frame->nChannels + 0];
    g_ch = ((uchar *)(bgr_frame->imageData + i*bgr_frame->widthStep))[j*bgr_frame->nChannels + 1];
    r_ch = ((uchar *)(bgr_frame->imageData + i*bgr_frame->widthStep))[j*bgr_frame->nChannels + 2];       
  }
}

Thanks and regards Himanshu

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2012-08-31 01:23:03 -0500

updated 2012-08-31 01:26:25 -0500

Hi Himanshu!

That seems about right. But if you are concerned about the execution speed, the following might be a bit faster (just extracted common operations out of the loop, a good compiler should be able to generate efficient loops for your code as well):

IplImage* bgr_frame = cvQueryFrame( capture );
int width, height, nchannels, step, offset;
int i, j, r_ch, b_ch, g_ch;

width = bgr_frame->width;
height = bgr_frame->height;
nchannels = bgr_frame->nChannels;
step = bgr_frame->widthStep;

for(i = 0 ; i < height ; i++) 
{
  uchar* data = (uchar*)(bgr_frame->imageData + i*step);
  for( j = 0 ; j < width ; j++)
  {
    offset = j * nchannels; //You should make sure that nchannels is 3
    b_ch = data[offset];
    g_ch = data[offset + 1];
    r_ch = data[offset + 2];
  }
}

Cheers!

edit flag offensive delete link more

Comments

Thanks; It's a good solution!

Himanshu gravatar imageHimanshu ( 2012-09-04 07:56:37 -0500 )edit
Login/Signup to Answer

Question Tools

Stats

Asked: 2012-08-30 14:01:48 -0500

Seen: 2,552 times

Last updated: Aug 31 '12