How to multiply a 3x3 kernel to a gray scale image (uint8) ?

조회 수: 9 (최근 30일)
theblueeyeswhitedragon
theblueeyeswhitedragon 2018년 8월 1일
댓글: Sonny Revell 2021년 12월 14일
Gx = [-1 0 1;-2 0 2;-1 0 1];
Gy = [-1 -2 -1; 0 0 0; 1 2 1];
img = imread('Bikesgray.jpg');
[rws, cls] = size(img);
mag = zeros(rws, cls);
for i = 1:rws - 2
for j = 1 : cls - 2
S1 = sum(sum(Gx.*img(i:i+2, j:j+2))); *
S2 = sum(sum(Gy.*img(i:i+2, j:j+2)));
mag(i+1, j+1) = sqrt(S1^2 + S2^2);
end
end
  • I get an error on this line saying: "Error using .* Integers can only be combined with integers of the same class,or scalar doubles." Converting img to double solves this problem, but it also makes the image white for some reason. Is there a way to multiply uint8 gray scale images to a 3x3 matrix?

채택된 답변

Rik
Rik 2018년 8월 1일
편집: Rik 2018년 8월 1일
You should indeed cast your image to double to avoid underflow and overflow. Another way to do this is to simply use the conv function family to do this convolution.
The reason for your image looking white is that a double is expected to have a value range from 0 to 1 and not 0 to 255. Casting back to uint8 will fix that, as would explicitly setting the caxis.
  댓글 수: 5
Rik
Rik 2018년 8월 3일
The internal convolution method is about 250 times faster than a nested loop by the way.
Sonny Revell
Sonny Revell 2021년 12월 14일
We know its faster but every image processing class makes you do the raw convolution process.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by