Hally
Hally

Reputation: 81

Convolution of image by Gaussian Coefficient on Matlab

clc;
clear all;
clc;

img = imread ('a.jpg');

img = rgb2gray(img);
figure, imshow(img);

img = double (img);

sigma= 2;
G= zeros(5,5);
for i=1:5
    for j=1:5
        x=[-2,1,0,-1,2];
        y=[-2,1,0,-1,2];
        G(i,j)= exp(-(x(i)^2+y(j)^2)/(2*(sigma^2)));
    end
end

G_=G/sum(sum(G,1),2);

A= conv2(img,G);

figure, imshow(A);

This is my code for image smoothing. I first calculated Gaussian Filter Coefficient Coefficient that is normalized.

For the last line, I tried to do convolution of image by the Gaussian Filter Coefficient, then show the image. However, it only shows a white empty image. I think the value for Gaussian Filter Coefficient is correct, so I think the problem is on convolution.

Isn't convolution done by conv2(u,v) on matlab? What am I doing wrong?

Upvotes: 2

Views: 608

Answers (1)

Rotem
Rotem

Reputation: 32084

Looks like there are two small issues:

  • img = double(img) converts the image type from uint8 to double.
    In MATLAB, image of type double applies pixels range [0, 1].
    All pixels above 1 are white, so the displayed image is white.
  • The kernel you are using with conv2 is not normalized.
    You are using A = conv2(img, G) when you want to use: A = conv2(img, G_).

For the first issue there are two options:

  1. Instead of img = double(img), you may use:
    img = im2double(img) (gives the same result as img = double(img)/255).
  2. Keep img = double(img), but convert to uint8 before imshow(A):
    imshow(uint8(A)).

Here is (one of the options) for corrected code:

clc
clear all

img = imread('a.jpg');

img = rgb2gray(img);
figure, imshow(img);

img = im2double(img); % im2double(img) instead of double(img).

sigma = 2;
G = zeros(5,5);
for i = 1:5
    for j = 1:5
        x = [-2,1,0,-1,2];
        y = [-2,1,0,-1,2];
        G(i,j) = exp(-(x(i)^2+y(j)^2)/(2*(sigma^2)));
    end
end

G_ = G/sum(sum(G,1),2);

A = conv2(img, G_); % G_ instead of G. For better margins: A = conv2(img, G_, 'same');

figure, imshow(A);

Upvotes: 2

Related Questions