kernel filtering in matlab

Kernel filtering is the process of modifying an image by applying a convolution operation between an image and a kernel. In Matlab, this can be achieved using the conv2 function, which performs 2-dimensional convolution.

The following code demonstrates an example of kernel filtering a grayscale image using a 3x3 kernel:

main.m
% Read image
img = imread('image.png');

% Define kernel
kernel = [1 1 1; 1 1 1; 1 1 1];

% Normalize kernel
kernel = kernel/sum(kernel,'all');

% Perform convolution
filtered_img = conv2(double(img),kernel,'same');

% Display original and filtered images
figure;
subplot(1,2,1); imshow(img); title('Original Image');
subplot(1,2,2); imshow(uint8(filtered_img)); title('Filtered Image');
388 chars
17 lines

In this example, the imread function reads in the grayscale image image.png. The kernel is defined as a 3x3 matrix of ones, and is normalized by dividing by the sum of all elements in the kernel. conv2 performs the convolution operation with the double converted image and the kernel, and the 'same' option specifies that the output has the same size as the input image. Finally, the original and filtered images are displayed side by side using the subplot and imshow functions.

Note that the same approach can be used for kernel filtering a color image by applying the convolution operation to each color channel separately.

gistlibby LogSnag