Saturday, 25 October 2014

Soft Focus Effect using Gaussian Filter


Today lets try out some cool image processing stuffs. One of my favorite is soft focus.  Here I shall discuss how to achieve in an easy way using MATLAB or Octave. We will discuss the same using OpenCV some other day. So lets get started...

Soft focus gives an effect of spherical aberration by introducing a blur in the back ground. This creates an illusion that except the main object, rest all will be out of focus. Below I am giving a code snippet to achieve it on MATLAB.

function softFocus(iFile, iFocusRadii, oFile)
%softFocus Creates soft focus effect on an image.
%   iFile - Input image file name
%   iFocusRadii - Radius of focus area.
%   oFile - Output file name
%
%   This method uses Gaussian LPF approach and a
%   mask to create pin hole effect on the focus area.
%   This uses center as focus locaton however one
%   can easily change the logic to dynamically change
%   the focus point.
%   Ex: softFocus('Test.jpg', 50, 'Out.jpg')

if nargin < 3
    error('Insufficient number of input params');
end

close all

img = imread(iFile);

h = fspecial('gaussian',5, 10);
out = imfilter(img,h);

sz = size(img);
width = sz(2);
height = sz(1);
radius = iFocusRadii;   % area of focus
centerW = width/2;     % point where focus should fall
centerH = height/2;     % point where focus should fall

figure, imshow(img), title('Original Image');

[x,y]=ginput(2);

% create a mask for point hole effect
[W,H] = meshgrid(1:width,1:height);
mask = sqrt((W-x).^2 + (H-y).^2) < radius;

mask = uint8(mask * 255);

% create a smoothened border
h = fspecial('gaussian',50, 10);
mask = imfilter(mask,h);
mask = mask / 255;

% smoothening between focus and non-focus areas
% still better reduce the mask size and apply only
% iFocusRadii + 10 area to reduce amount of processing
for i = 1:height
    for j = 1: width
    alpha = mask(i, j);
 
    img1(i, j, :) = alpha * img(i, j, :) + (1 - alpha) * out(i, j, :);
 
    end
end

figure, imshow(img1), title('Soft Focused Image');

imwrite(img1, oFile);
end

Results:

The following images shows the effect of focus on fishes.

Input Image


Output Image



Below images shows a focus effect on kitten's face.

Input Image


Output Image



One could try out a lot of combinations to get better effects.

Next time we will discuss about more image effects. 
Till then keep Hac-King...






No comments:

Post a Comment