how to iterate 5x5 window over mat image

asked 2014-10-21 00:37:52 -0500

Deepak Kumar gravatar image

updated 2014-10-21 00:39:14 -0500

hi, i am having problem while iterating a 5x5 window over a mat image. it iterates along column but it crashes when new row comes. what should i do. i am doing this to find local standard deviation.

here is the code:-

Mat block;

Mat inner = cv::imread("C:\\Users\\Intern-3\\Desktop\\processed\\edited.png",0);
int row = inner.rows; int col = inner.cols;
cv::imshow("Original Image", inner); // show the image

imwrite( "C:\\Users\\Intern-3\\Desktop\\processed\\original.jpg", inner );
cerr << inner.rows << endl;
cerr << inner.cols << endl;
cout<<"RowsLast = "<<endl<<" "<<inner.col(col)<<endl;

Mat outer = Mat(inner.rows+2, inner.cols+2, inner.type());
copyMakeBorder(inner,outer ,1,1,1,1,BORDER_REPLICATE);
row = outer.rows;
cerr << outer.rows << endl;
cerr << outer.cols << endl;

cv::imshow("Processed Image", outer); // show the image
imwrite( "C:\\Users\\Intern-3\\Desktop\\processed\\processed.jpg", outer );
cout<<"RowsLast = "<<endl<<" "<<outer.col(col)<<endl;

block = (outer(Rect(0,0,4,4)));

for(int i=2;i<row+2;i++)
    for(int j=2;j<col+2;j++)
            int sum1=0;
        int sum2=0;

        block = outer.rowRange(i-2,i+2).colRange(j-2,j+2);

        for(int x=0;x<5;x++)
            for(int y=0;y<5;y++)
                sum1=sum1+<uchar>(x, y);  // Addition of all elements
      <uchar>(x,y)*<uchar>(x,y); //Addition of all element square
                cout<<"Y = "<<y<<endl;

        double mean = sum1/25;  
        double variance=-(mean*mean -(sum2/25)); //Variance
        double deviation=sqrt(variance);         //Standard deviation

        //Storing deviation value at pixel position in output image<uchar>(i-2,j-2)=deviation;  




edit retag flag offensive close merge delete


for(int i=2;i<row+2;i++) // if you want to spare a 2 pixel border, that has to be row-2 (same for cols)

berak gravatar imageberak ( 2014-10-21 01:53:31 -0500 )edit

sorry, i didnt get you, can you explain bit more

Deepak Kumar gravatar imageDeepak Kumar ( 2014-10-21 02:04:52 -0500 )edit

you need: for(int i=2;i<row-2;i++) and for(int j=2;j<col-2;j++)

your current code goes out of bounds there.

berak gravatar imageberak ( 2014-10-21 02:07:11 -0500 )edit

i<row+2 will give you segmentation fault, the maximum value for row is row and you are trying to access row+1+2, Just change it to i<row-2

thdrksdfthmn gravatar imagethdrksdfthmn ( 2014-10-21 02:08:12 -0500 )edit