tags:

views:

1337

answers:

4

I'm using OpenCV for object detection and one of the operations I would like to be able to perform is a per-pixel square root. I imagine the loop would be something like:

IplImage* img_;
...
for (int y = 0; y < img_->height; y++) {
  for(int x = 0; x < img_->width; x++) {
    // Take pixel square root here
  }
}

My question is how can I access the pixel value at coordinates (x, y) in an IplImage object?

+2  A: 

Assuming img_ is of type IplImage, and assuming 16 bit unsigned integer data, I would say

unsigned short pixel_value = ((unsigned short *)&(img_->imageData[img_->widthStep * y]))[x];

See also here for IplImage definition.

Rutger Nijlunsing
Thanks, this definitely helped :)
Eric Scrivner
And I even don't know OpenCV at all :)
Rutger Nijlunsing
+1  A: 

OpenCV IplImage is a one dimensional array. You must create a single index to get at image data. The position of your pixel will be based on the color depth, and number of channels in your image.

// width step 
int ws = img_->withStep;
// the number of channels (colors)
int nc = img_->nChannels;
// the depth in bytes of the color 
int d = img_->depth&0x0000ffff) >> 3;
//  assuming the depth is the size of a short
unsigned short * pixel_value = (img_->imageData)+((y*ws)+(x*nc*d));
// this gives you a pointer to the first color in a pixel
//if your are rolling grayscale just dereference the pointer.

You can pick a channel (color) by moving over pixel pointer pixel_value++. I would suggest using a look up table for square roots of pixels if this is going to be any sort of real time application.

Kat
A: 

You may find several ways of reaching image elements in Gady Agam's nice OpenCV tutorial here.

rics
A: 

please use the CV_IMAGE_ELEM macro. Also, consider using cvPow with power=0.5 instead of working on pixels yourself, which should be avoided anyways