Partially bluring image with averaging filter

Viewed 84

i created this function in order to to partially blur an image :

function [ T ] = floutage(I,XA,YA,XB,YB)
H=fspecial('average',[11 11]);
t=0;
for i=XA:XB
    for j=YA:YB
        t=imfilter(I(i,j),H) ; 
        I(i,j)=t;
    end   
end
T=I;
end

and i call it in the script like this :

T1=floutage(Iref,10,10,350,350);
figure
imshow(T1);

but the result is no bluring but a black box :

the result that i got

2 Answers

Blurring Portion/Partition of Image

The imfilter() function covers/handles the convolution process allowing us to skip on implementing the for-loops. To filter the portion of the image the portion can be passed directly to the imfilter() function and the blurred portion will be returned. After the blurred portion is returned the corresponding portion of the original image can be overwritten by indexing.

To handle the padding along the border I used the 'replicate' property which is one handling method among many: MATLAB Documentation: imfilter; Boundary Options.

Blurring Portion/Partition of Image

Iref = rgb2gray(imread("peppers.png"));
[T1] = floutage(Iref,10,10,350,350);
imshow(T1);

function [Iref] = floutage(Iref,XA,YA,XB,YB)
H = fspecial('average',[11 11]);

%Grabbing portion of image to be blurred%
Sub_Image = Iref(YA:YB,XA:XB);

%Filtering/convolving the portion of the image%
Blurred_Sub_Image = imfilter(Sub_Image,H,'replicate'); 

%Replacing the old portion with the blurred portion%
Iref(YA:YB,XA:XB) = Blurred_Sub_Image; 
end

Here's a simple alternative to MichaelTr7's answer. Instead of applying the blur on the image region only, we apply it to the whole image (this is cheap anyway) and then cut out a portion of the blurred result to paste into the original image. In general this gives a better representation of the blur towards the edges of the box:

img = rgb2gray(imread('peppers.png'));
out = floutage(img,120,250,180,310);
imshow(out);

function img = floutage(img, XA, YA, XB, YB)
% Filter the whole image
H = fspecial('average', [11 11]);
blur = imfilter(img, H); 
% Write blurry box into image
img(YA:YB, XA:XB) = blur(YA:YB, XA:XB);
end

output of function floutage

One advantage of this method is that it directly leads to a way to avoid the sharp edges of the blurry box: apply a feather. This is one way of implementing that:

function img = floutage2(img, XA, YA, XB, YB)
% We'll be working with doubles
img = double(img);
% Filter the whole image
H = fspecial('average', [11 11]);
blur = imfilter(img, H); 
% Create mask
mask = zeros(size(blur));
mask(YA:YB, XA:XB) = 1;
mask = imfilter(mask, H);
% Write blurry box into image by weighting with mask
img = blur .* mask + img .* (1 - mask);
% Convert back to uint8
img = uint8(img);
end

output of the function floutage2

Related