MATLAB Answers

0

How to convolve an image with a 2D function and plot the result

Asked by David Okeson on 14 Oct 2018
Latest activity Commented on by Image Analyst
on 14 Oct 2018
Hi, I have a bar phantom image attached that I want to convolve with the 2d function h1(x,y)=e^(-5x^2-5y^2). I'm not very familiar with Matlab or similar programs so bear with me.
I have created and plotted the function h1 using the following code:
x = [-1: .01: 1];
y = [-1: .01: 1];
[x_,y_] = meshgrid(x,y);
h1_ = exp((-5.*x_.^2)-(5.*y_.^2));
surf(x_,y_,h1_)
I then inserted the bar phantom image into Matlab using:
I = imread('bar phantom1.png');
From here I'm stuck and I've tried a number of things unsuccessfully. I've tried:
H1_ = abs(fft2(h1_));
I1 = abs(fft2(I));
g = ifft2(H1_.*I1);
And get the error: Array dimensions must match for binary array op.
I tried changing the dimensions of my x and y variables to match the dimensions of my image but the result g is a blank white image.
I also played tried to avoid using fft2 using imfilter, double, and conv2 but only got all white or black resulting images. Any help would be greatly appreciated.

  0 Comments

Sign in to comment.

1 Answer

Answer by Image Analyst
on 14 Oct 2018
 Accepted Answer

Try this:
kernel = h1_ / sum(h1_(:));
filteredImage = conv2(double(I), kernel, 'same');
imshow(filteredImage, []);

  2 Comments

When entering
filteredImage = conv2(double(I), kernel, 'same');
I got the error
Error using conv2
N-D arrays are not supported.
I figured out how to fix this though, the bar phantom I was a 484x307x3 matrix, I used rgb2gray to create a new image of size 484x307 and it worked perfectly.
Thank you.
For a color image, you can use imfilter() or split the color image into individual color channels and process each one at a time:
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
filteredImageR = conv2(double(redChannel), kernel, 'same');
filteredImageG = conv2(double(greenChannel), kernel, 'same');
filteredImageB = conv2(double(blueChannel), kernel, 'same');

Sign in to comment.