how to iterate 5x5 window over mat image

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

Deepak Kumar gravatar image

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

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;
row--;
col--;
cout<<"RowsLast = "<<endl<<" "<<inner.col(col)<<endl;
cout<<"-------------------\n"<<endl;

Mat outer = Mat(inner.rows+2, inner.cols+2, inner.type());
copyMakeBorder(inner,outer ,1,1,1,1,BORDER_REPLICATE);
row = outer.rows;
col=outer.cols;
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 );
col--;
cout<<"RowsLast = "<<endl<<" "<<outer.col(col)<<endl;
cout<<"-------------------\n"<<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+ block.at<uchar>(x, y);  // Addition of all elements
                sum2=sum2+block.at<uchar>(x,y)*block.at<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
        block.at<uchar>(i-2,j-2)=deviation;  

    }
}

waitKey(0);

}

edit retag flag offensive close merge delete

Comments

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 -0600 )edit

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

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

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 -0600 )edit
2

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 -0600 )edit