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

278 views (last 30 days)
theblueeyeswhitedragon on 1 Aug 2018
Commented: Rik on 3 Aug 2018
Gx = [-1 0 1;-2 0 2;-1 0 1];
Gy = [-1 -2 -1; 0 0 0; 1 2 1];
[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 on 1 Aug 2018
Edited: Rik on 1 Aug 2018
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.

Show 1 older comment
Rik on 2 Aug 2018
Your double loop can be replaced by the conv2 function to calculate S1 and S2. Then for the root square I would still cast to double. (I can't test code at the moment btw)
Rik on 3 Aug 2018
For a fully working example, see below.
Gx = [-1 0 1;-2 0 2;-1 0 1];
Gy = [-1 -2 -1; 0 0 0; 1 2 1];
S1 = conv2(img,Gx,'same');
S2 = conv2(img,Gy,'same');
mag1 = uint8(sqrt(S1.^2 + S2.^2));
[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)));
mag2(i+1, j+1) = sqrt(S1^2 + S2^2);
end
end
mag2=uint8(mag2);
%To make mag1 equal to mag2, the left and upper border need to be set to 0
%and the lower and right border need to be removed.
mag1b=mag1(1:end-1,1:end-1);
mag1b(:,1)=0;mag1b(1,:)=0;
figure(1),clf(1)
subplot(1,2,1)
imshow(mag2,[0 255])
title('with loop')
subplot(1,2,2)
imshow(mag1,[0 255])
title('with convolution')
if isequal(mag1b,mag2)
disp('convolution and loop are equal after correction')
else
disp('convolution and loop are *not* equal after correction')
end
Rik on 3 Aug 2018
The internal convolution method is about 250 times faster than a nested loop by the way.

R2017b

### Community Treasure Hunt

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

Start Hunting!