C++ Blur function to MATLAB code

조회 수: 3 (최근 30일)
Anish Ardjoon
Anish Ardjoon 2021년 1월 6일
댓글: Anish Ardjoon 2021년 1월 7일
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));

채택된 답변

Jan
Jan 2021년 1월 6일
편집: Jan 2021년 1월 6일
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
  댓글 수: 1
Anish Ardjoon
Anish Ardjoon 2021년 1월 7일
Works like a charm, thank you for your help :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by