C++ Blur function to MATLAB code

3 views (last 30 days)
Anish Ardjoon
Anish Ardjoon on 6 Jan 2021
Commented: Anish Ardjoon on 7 Jan 2021
Hi i am trying to convert a blur function I implemented in C++ to MATLAB code, I am getting an error when trying to compute the sum of all elements in an array
Index exceeds the number of array elements (1).
Below is the C++ code.
Mat BlurFunc(Mat Grey, int winsize)
{
Mat Blur = Mat::zeros(Grey.size(), CV_8UC1);
for (int i = winsize; i < Grey.rows - winsize; i++)
{
for (int j = winsize; j < Grey.cols - winsize; j++)
{
int sum = 0;
for (int ii = -winsize; ii <= winsize; ii++)
{
for (int jj = -winsize; jj <= winsize; jj++)
{
sum += Grey.at<uchar>(i + ii, j + jj);
}
}
Blur.at<uchar>(i, j) = sum / ((winsize * 2 + 1) * (winsize * 2 + 1));
}
}
return Blur;
}
and this is what I am trying to get to work.
grey_img = rgb2gray(img);
y = size(grey_img);
for i=3:(rows-3)
for j=3:(cols-3)
A = grey_img(i-2:i,j-2:j);
sum = sum(A(:));
y(i,j) = sum/49;
end
end
imshow(uint8(y));

Accepted Answer

Jan
Jan on 6 Jan 2021
Edited: Jan on 6 Jan 2021
You have redefined the function name "sum" as name of a variable. After sum=sum(A(:)) the symbol "sum" is a variable. The next time you call "sum(A(:))", A(:) is treated as index.
Solution: Use another name:
for i=3:(rows-3)
for j=3:(cols-3)
A = grey_img(i-2:i,j-2:j);
S = sum(A(:));
y(i,j) = S / 49;
end
end
Notes:
  • For the average over 9 elements you have to divide by 9, not 49.
  • The 3 rightmost columns and the 3 rows on the bottom are not considered in your code.
  • Compared with the C++ code, the output is shifted.
  • You have defined y = size(grey_img) , but later on y is the output matrix. rows and columns are not defined.
W = winsize; % Shorter name
[rows, cols] = size(grey_img);
Blur = zeros(rows, cols); % Pre-allocate
Div = (2 * W + 1)^2;
for i = W+1:(rows - W)
for j = W+1:(cols - W)
Window = grey_img(i-W:i+W, j-W:j+W);
Blur(i,j) = sum(Window(:)) / Div;
end
end

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!