tags:

views:

22

answers:

1

Hi,

I have a function that I would like to apply to each pixel in a YUN image (call it src). I would like the output to be saved to a separate image, call it (dst).

I know I can achieve this through pointer arithmetic and accessing the underlying matrix of the image. I was wondering if there was a easier way, say a predefined "map" function that allows me to map a function to all the pixels?

Thanks,

A: 

Since I don't know what a YUN image is, I'll assume you know how to convert RGB to that format.

I'm not aware of an easy way to do the map function you mentioned. Anyway, OpenCV has a few predefined functions to do image conversion, including

cvCvtColor(color_frame, gray_frame, CV_BGR2GRAY);

which you might want to take a closer look.

If you would like to do your own, you would need to access each pixel of the image individually, and this code shows you how to do it (the code below skips all kinds of error and return checks for the sake of simplicity):

// Loading src image 
IplImage* src_img = cvLoadImage("input.png", CV_LOAD_IMAGE_UNCHANGED); 
int width = src_img->width; 
int height = src_img->height;
int bpp = src_img->nChannels; 

// Temporary buffer to save the modified image
char* buff = new char[width * height * bpp];

// Loop to iterate over each pixel of the original img
for (int i=0; i < width*height*bpp; i+=bpp) 
{
  /* Perform pixel operation inside this loop */

  if (!(i % (width*bpp))) // printing empty line for better readability
      std::cout << std::endl;

   std::cout << std::dec << "R:" << (int) src_img->imageData[i] <<  
                            " G:" << (int) src_img->imageData[i+1] <<  
                            " B:" << (int) src_img->imageData[i+2] << " "; 

  /* Let's say you wanted to do a lazy grayscale conversion */
  char gray = (src_img->imageData[i] + src_img->imageData[i+1] + src_img->imageData[i+2]) / 3;
  buff[i] = gray;
  buff[i+1] = gray;
  buff[i+2] = gray;
}

IplImage* dst_img = cvCreateImage(cvSize(width, height), src_img->depth, bpp);  
dst_img->imageData = buff;

if (!cvSaveImage("output.png", dst_img))
{
  std::cout << "ERROR: Failed cvSaveImage" << std::endl;
}

Basically, the code loads a RGB image from the hard disk and performs a grayscale conversion on each pixel of the image, saving it to a temporary buffer. Later, it will create another IplImage with the grayscale data and then it will save it to a file on the disk.

karlphillip