Custom functions for complex tasks

A function can be thought of as a black box, which produces output results when fed with proper inputs. We have already used several ready-made functions so far, but we haven't made any functions of our own. The biggest advantage of making our own functions is that we can reuse them with different inputs to produce different results, as opposed to scripts where inputs must usually be changed by altering and resaving the source code.

To begin, let's attempt to mix all the aforementioned enhancement methods in a single function that will accept the choice of method from the input. More specifically, we will make a function that will take two inputs; an image and a number. The image will be enhanced using the method denoted by the number. After opening the Editor, we type in the following code:

function [output] = ContrastEnhancement(input,method)

% Function that performs image contrast enhancement with methods
% incorporated in MATLAB toolboxes
% Inputs:
%           input - Input image
%           method - Enhancement method (1: histeq, 2: imadjust, 
%                                        3: adapthisteq)
% Output:   
%           output - Output image (with enhanced contrast)

switch method
case 1
output = histeq(input);
case 2
output = imadjust(input);
case 3
output = adapthisteq(input);
end

When we are done, we can save the function using the name that is already chosen (ContrastEnhancement.m). We don't need to explain a lot here, since the basic idea is rather simple. The function includes the three enhancement methods already explained earlier. To choose which one to use on the input image, the method input must be set to 1 if we want to use histeq, 2 if we want to use imadjust, and 3 if we want to use adapthisteq. The selection is made using the switch case structure, which is a very widely used method in programming. The switch command defines which variable will be checked and the case commands check for all acceptable values and connects them to their respective tasks. To see if our function actually works, let's use it on another version of the holiday picture we used in the previous chapter:

>> img = imread('holiday_image2.bmp');
>> subplot(2,2,1),imshow(img),title('Original Image');
>> subplot(2,2,2),imshow(ContrastEnhancement(img,1)),title('Histeq result');
>> subplot(2,2,3),imshow(ContrastEnhancement(img,2)),title('Imadjust result');
>> subplot(2,2,4),imshow(ContrastEnhancement(img,3)),title('Adapthisteq result');

The result reveals the very important role that adaptive histogram equalization can play in enhancing images with varying illumination.

While both histeq and adapthisteq have managed to lighten the left part of the image, the latter has not only achieved a better result at it, but also has avoided saturating smooth areas like histeq. In order to understand this a little better, let's use imtool to zoom in the areas with bigger differences.