- 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.
C++ Blur function to MATLAB code
조회 수: 3 (최근 30일)
이전 댓글 표시
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));
댓글 수: 0
채택된 답변
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:
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!