1

If we access pixel by a pointer using step and data of Mat Image. see example below

int step = srcimg.step; 
for (int j = 0; j < srcimg.rows; j++) {
    for (int i = 0; i < srcimg.cols; i++) {

         //this is pointer to the pixel value. 
         uchar* ptr = srcimg.data + step* j + i;
    }
}

Question: How can we perform 3x3 weighted avg operations with image step by a pointer? thanks

Abc
  • 824
  • 2
  • 7
  • 20
  • I have posted a blur filter example here: [link](http://stackoverflow.com/questions/38205177/small-color-defects-when-aplying-mean-filter-on-images/38211331#38211331). It should be simple to modify my code sample to perform 3x3 weighted avg. – Rotem Jul 09 '16 at 13:24

2 Answers2

1

You mustn't use data field in opencv because memory is not allways continuous. you can check this using isContinuous() method.

Now you can do like this (image type is CV_8UC1)

for (int i = 1; i < srcimg.rows-1; i++) 
{
    for (int j = 1; j < srcimg.cols-1; j++) 
    {

        int  x=0;
        for (int k=-1;k<=1;k++)
        {
             uchar* ptr=srcimg.ptr(k+i)+j-1; 
             for (int l=-1;l<=1;l++,ptr++)
                 x +=*ptr;
        }
    }
}

image border are not processed. Now if you want to blur an image use blur method

You can use this post too

Community
  • 1
  • 1
LBerger
  • 593
  • 2
  • 12
  • I think. when image is passed by 'imread ()'. it is created.so it garmented to be continuous. In that case, we can use data field in opencv. – Abc Jul 09 '16 at 10:34
  • [May be](http://stackoverflow.com/questions/33665241/is-opencv-matrix-data-guaranteed-to-be-continuous). You didn't say it that imread was used in your question. But that's not important. [ptr](http://docs.opencv.org/master/d3/d63/classcv_1_1Mat.html#a13acd320291229615ef15f96ff1ff738) is a good method to write pixel. data can be null with a non [empty matrix](http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat) – LBerger Jul 09 '16 at 12:19
1

I am doing something like this .

        int sr = 3;
        for (int j = 0; j < srcimg.rows; j++) {
            for (int i = 0; i < srcimg.cols; i++) {

                uchar* cp_imptr = im.data;
                uchar* tptr = im.data + imstep *(sr + j) + (sr + i);

                int val_tptr = cp_imptr [imstep *(sr + j) + (sr + i)]; //pointer of image data amd step at 3x3 

                int val_cp_imptr = cp_imptr[imstep *j + i];

                double s = 0;

                for (int n = templeteWindowSize; n--;)
                {
                    for (int m = templeteWindowSize; m--;)
                    {
                        uchar* t = tptr;      //pointer of template 

                        // sum 
                        s += *t;
                        t++;
                    }
                    t += cstep;
                }
            }
            cout << endl;
        }
Abc
  • 824
  • 2
  • 7
  • 20