Vectoring the blurring of an image, with use of a kernel

56 views (last 30 days)
Hello,
I have to blur an image with use of a kernel. Currently I have several for loops, however, this is slow. I was wondering how I could go about vectorising it while only using functions from base matlab (no toolboxes unfortunatly). I'm very new to matlab so any help would be greatly appreciated. My current code is below:
inputImage = imread("testImage2.jpg");
inputImage = double(inputImage);
w = 5; % specifies the size of the box (w = 3 means a 3x3 box)
r = fix(w/2); % 'radius' of box, excluding centre pixel
[x,y,z] = size(inputImage); % 3D sizes of image
blurredImage = zeros(size(inputImage)); % initialize output array
for i=(r+1):x-(r+1) % scan through every pixel in inputImage
for j=(r+1):y-(r+1) % '(rad+1)' leaves a border so data isn't read outside array bounds
for (k=1:3) % scan through rgb values of each pixel
kernel = inputImage([i-r:i+r],[j-r:j+r], k); % array index the pixel data within the box around the current pixel
blurredImage(i,j,k) = mean(kernel(:)); % apply mean of pixel data within box to blurredImage pixel
end
end
end
figure(1)
image(uint8(inputImage))
figure(2)
image(uint8(blurredImage))
  1 Comment
Zachary Cockshutt
Zachary Cockshutt on 22 May 2020
I had an attempt at vectorising and came up with this, however, it just ouputs a grey image:
i1 = double(imread("IMG_5704.JPG"));
dim = size(i1);
iOutput = zeros(size(i1));
w = 5; % specifies the size of the box (w = 3 means a 3x3 box)
r = fix(w/2); % 'radius' of box, excluding centre pixel
i = (r+1):dim(1)-(r+1);
j = (r+1):dim(2)-(r+1);
kernel = i1([i-r:i+r],[j-r:j+r],:);
iBlur(i,j,:) = mean(kernel,'all');

Sign in to comment.

Accepted Answer

Raunak Gupta
Raunak Gupta on 26 May 2020
Hi,
Without Toolboxes such as Image Processing Toolbox I see the only way achieving the kernel multiplication with the help of conv2. Here since the kernel is doing averaging that is why convolution definition will not alter the result. Using the ‘shape’ name-value as ‘same’ you may get the blurred image. Use the kernel as mentioned below based on window size. Apply the same kernel on each channel and final image should be same as done by imfilter.
windowSize = 5;
kernel = ones(windowSize) / windowSize^2;

More Answers (0)

Community Treasure Hunt

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

Start Hunting!