Q:

How to load nearby pixels using pointer

Suppose i have an image matrix and i am at a particular pixel [say 4] like this:
 0  1  2  
 3 `4` 5  
 6  7  8

I am trying to cycle through all pixels and am attempting to access 0,1,2, 3,5 6,7,8 whose values i am storing in the array called Pixel.... here is my attempt at it using OpenCV, kindly tell me where am i going wrong.
I am using  pointer temp_ptr to access the IplImage image.
    uchar* temp_ptr=0 ;
    CvScalar Pixel[3][3];
    int rows=image->height,cols=image->width,row,col;
    for( row = 0; row < rows-2; ++row) 
    {
        for ( col = 0; col < cols-2; ++col) 
            {               
                    temp_ptr  = &((uchar*)(image->imageData + (image->widthStep*row)))[col*3];
                    for (int krow = -1 ; krow <= 1; krow++)
                    {
                        for (int kcol = -1; kcol <= 1; kcol++)
                        {       
                        temp_ptr  = &((uchar*)(image->imageData + (image->widthStep*row+krow)))[(col+kcol)*3];
                            for(int i=0; i < 3; i++)
                            {
                                for(int j=0; j < 3; j++)
                                {
                                    for(int k=0; k < 3; k++)
                                    {
                                        Pixel[i][j].val[k]=temp_ptr[k];
                                    }
                                }
                            }

                        }
                    }
             }
    }

I am not really sure how to load the sorrounding Pixels usingtemp_ptr, please help me out.

A:

Well sir, it sounds like you want to do convolution, and doing it this way when you have OpenCV at your fingertips is a bit like hammering a can opener on your Spaghettios to burst it open by blunt force. 
In fact, what you're doing is almost exactly the output of cv::blur(src, dst, cv::Size(3,3)) except it also includes the center pixel in the average.
If you want to exclude the center pixel then you can create a custom kernel - just a matrix with appropriate weights:
[.125 .125 .125
 .125  0   .125
 .125 .125 .125 ]

and apply this to the image with cv::filter2d(src, dst, -1, kernel).

