# Convert them to grayscale. Write a function, convolve, which takes a filter, F, and an image, I, as input and calculates the 2D convolutions of I with F via the use of ‘for’

14 views (last 30 days)
Mohamed arsh Khatib on 12 Mar 2023
Commented: DGM on 12 Mar 2023
Load the Old house.jpg image. Convert them to grayscale. Write a function, convolve, which takes a filter, F, and an image, I, as input and calculates the 2D convolutions of I with F via the use of ‘for’ loops. Zero-pad the image within the function to ensure that the filtered image is the same size as the original image. You may assume that F always has an odd value for its height and width. DO NOT USE the existing conv, conv2, convn, filter, or filter2 functions. Apply a 15×15 Gaussian filter with a standard deviation of 5 to both images using the convolve function. Show the results.
code:
function outImg = convolve(img, filter)
% Get the dimensions of the filter and the image
[filterHeight, filterWidth] = size(filter);
[imgHeight, imgWidth] = size(img);
% Calculate the padding required for each dimension
% Create a zero-padded version of the image
% Create an output image of the same size as the input image
outImg = zeros(size(img));
% Perform 2D convolution using nested for loops
for i = 1:imgHeight
for j = 1:imgWidth
% Extract the current patch from the padded image
% Multiply the patch by the filter and sum the result
result = sum(sum(patch .* filter));
% Assign the result to the output image
outImg(i,j) = result;
end
end
end
% Convert the image to grayscale
imgGray = rgb2gray(img);
% Create a 15x15 Gaussian filter with a standard deviation of 5
filterSize = 15;
sigma = 5;
filter = fspecial('gaussian', filterSize, sigma);
% Apply the filter to the grayscale image using the convolve function
filteredImgGray = convolve(imgGray, filter);
% Apply the filter to the original image by filtering each color channel separately
filteredImg = zeros(size(img));
for i = 1:3
filteredImg(:,:,i) = convolve(img(:,:,i), filter);
end
% Display the filtered grayscale image
imshow(filteredImgGray, []);
% Display the filtered original image
figure;
imshow(filteredImg);
error:
Error: File: untitled1.m Line: 32 Column: 1
This statement is not inside any function.
(It follows the END that terminates the definition of the function
"convolve".)

Jan on 12 Mar 2023
outImg(i,j) = result;
end
end
end % <== This END closes the function
All code after this end is outside of a function and therefore no valid Matlab syntax. This is explained in the error message clearly, isn't it?
DGM on 12 Mar 2023

### Categories

Find more on Image Category Classification in Help Center and File Exchange

R2021a

### Community Treasure Hunt

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

Start Hunting!