Dip Paper-1 Sec II

download Dip Paper-1 Sec II

of 47

Transcript of Dip Paper-1 Sec II

  • 8/3/2019 Dip Paper-1 Sec II

    1/47

    Digital Image Processing Paper I Section II

    Digital Image Processing

    M.Sc. (Comp Sci) Part II 1

  • 8/3/2019 Dip Paper-1 Sec II

    2/47

    Digital Image Processing Paper I Section II

    INDEX

    SR

    No. DATE TOPIC

    PAGE

    NO SIGN

    1Image Enhancement in Spatial Domain

    2Image Enhancement in Frequency Domain

    3Image Enhancement Statistical Filters

    4Lossy Image Compression

    5Image Segmentation

    6Region Filling

    7Morphological Operations

    M.Sc. (Comp Sci) Part II 2

  • 8/3/2019 Dip Paper-1 Sec II

    3/47

    Digital Image Processing Paper I Section II

    Practical No. 1

    Image Enhancement in Spatial Domain

    Aim: To apply the following image enhancement algorithms to the given input image:

    (i) Contrast stretching: Display dark, bright, low-contrast and high contrast images by applyingcontrast stretching on an input image by manipulating the mapped gray-levels in an input

    image.

    (ii) Histogram Equalization: Apply the histogram equalization technique on an input image.

    (iii) Image averaging: Implement image averaging technique to remove the noise from an imageby using an averaging filter.

    (iv) Smoothing: Apply the smoothing effect to an input image by using appropriate filter masks.

    Description:

    1. Contrast Stretching: Contrast Stretching is basically a mapping transformation function of theform

    s = T(r)

    where r & s are variables denoting, respectively, the gray level of f (x, y) and g (x, y) at any

    point (x, y) of the image.

    This transformation is used in order to produce an image of higher contrast than the original by

    darkening the levels below some arbitrary constant m and brightening the levels above m intheoriginal image. Hence, the values of rbelow m are compressed by the transformation function

    into a narrow range of s, toward black. The opposite effect takes place for values ofrabove m.

    2. Histogram Equalization: It reassigns the brightness values of pixels based on the imagehistogram. Individual pixels retain their brightness order (that is, they remain brighter or darker

    than other pixels) but the values are shifted, so that an equal number of pixels have each possible

    brightness value. For each brightness level j in the original image and its histogram, the new

    assigned value k is calculated as below. In many cases, this spreads out the values in regions

    where different regions meet, showing detail in areas with a high brightness gradient.

    =

    =j

    i

    i

    T

    Nk

    0

    Ni= Number of pixels with brightness value I.

    T = Total number of pixels in the image.

    3. Image Averaging: When images of an unchanging scene are corrupted by random noise, a

    sequence of these images can be averaged together in order to reduce the effects of the noise. This

    works because noise perturbs pixel grey levels, and a positive perturbation of a given magnitude

    tends to be just as likely as a negative perturbation of the same magnitude. Hence there is a

    tendency for these 'errors' in pixel grey level to cancel each other out to an increasing degree, as

    the number of averaged images increases.

    M.Sc. (Comp Sci) Part II 3

  • 8/3/2019 Dip Paper-1 Sec II

    4/47

    Digital Image Processing Paper I Section II

    4. Smoothing: Smoothing filters are used for blurring and for noise reduction. Blurring can be used

    for removal of small details from and image prior to object extraction, and bridging of small gaps

    in lines or curves. Noise reduction can be accomplished by blurring with a linear filter and also

    by non-linear filtering. The smoothing function in this practical is performed using a given filter

    mask (low pass filters).By replacing the value of every pixel in an image by the average of thegray levels in the neighborhood defined by the filter, smoothing results in an image with reduced

    sharp transitions in gray levels. As random noise typically consists of sharp transitions in gray

    levels, the most obvious application of smoothing is noise reduction.

    In general linear filtering of an imagefof size M x N with a filter mask of size m x n is given bythe expression:

    a bg(x, y) = w(s, t) f(x + s, y + t)

    s=-a s=-b

    Where a = (m - 1)/2 and b = (n - 1)/2. To generate a complete filtered image this equation must be

    applied for x = 0,1,2,., M 1 and y = 0,1,2,., N 1.

    As an example of smoothing, from above equation , the general implementation for filtering an M

    x N image with a weighted averaging filter of size m x n (m and n odd) is given by theexpression

    a b

    g(x, y) = w(s, t) f(x + s, y + t)s=-a s=-b

    a b w(s, t)

    s=-a s=-b

    The denominator in above equation is simply the sum of the mask coefficients and, there fore, it

    is a constant that needs to be computed only once. Typically, this scale factor is applied to all the

    pixels of the output image after the filtering process is completed.

    M.Sc. (Comp Sci) Part II 4

  • 8/3/2019 Dip Paper-1 Sec II

    5/47

    Digital Image Processing Paper I Section II

    Source code: (Contrast Stretching)

    f = imread(rice.tif');

    subplot(2,2,1); imshow(f); title('Original Image');

    subplot(2,2,2); imhist(f); title('Histogram');

    figure;

    g = imadjust(f,[0 1],[0.2 0.4]);

    subplot(2,2,1); imshow(g); title('Dark Image');

    subplot(2,2,2); imhist(g); title('Histogram');

    g = imadjust(f,[0 1],[0.6 1.0]);

    subplot(2,2,3); imshow(g); title('Bright Image');

    subplot(2,2,4); imhist(g); title('Histogram');

    figure;

    g = imadjust(f,[0 1],[0.4 0.7]);

    subplot(2,2,1); imshow(g); title('Low-contrast image');subplot(2,2,2); imhist(g); title('Histogram');

    g = imadjust(f,[0 1],[0.1 1.0]);

    subplot(2,2,3); imshow(g); title('High-contrast image');

    subplot(2,2,4); imhist(g); title('Histogram');

    Functions used:

    a. imread (filename): Read image from graphics files.

    b. imshow(): Display an image.

    c. imhist(): Display a histogram of image data.

    d. imadjust(I,[low_in high_in],[low_out high_out],gamma): Adjust image intensity valuesor colormap. This function maps the values in intensity image I to new values in J such that

    values between low_in and high_in map to values between low_out and high_out. Values below

    low_in and above high_in are clipped; that is, values below low_in map to low_out, and those

    above high_in map to high_out.

    M.Sc. (Comp Sci) Part II 5

  • 8/3/2019 Dip Paper-1 Sec II

    6/47

    Digital Image Processing Paper I Section II

    Output:

    M.Sc. (Comp Sci) Part II 6

  • 8/3/2019 Dip Paper-1 Sec II

    7/47

    Digital Image Processing Paper I Section II

    M.Sc. (Comp Sci) Part II 7

  • 8/3/2019 Dip Paper-1 Sec II

    8/47

  • 8/3/2019 Dip Paper-1 Sec II

    9/47

    Digital Image Processing Paper I Section II

    Source code:(Histogram Equalization)

    f = imread('ngc4024m.tif');

    g = histeq(f);

    title('Histogram');

    subplot(2,2,1);

    imshow(f);

    title('Input Image');

    subplot(2,2,2);

    imhist(f);

    title('Histogram');

    subplot(2,2,3);

    imshow(g);

    title('Image after Histogram Equalization');

    subplot(2,2,4);imhist(g);

    title('Histogram');

    Functions used:

    a. histeq():Enhances the contrast of images by transforming the values in an intensity image, or the

    values in the colormap of an indexed image, so that the histogram of the output image

    approximately matches a specified histogram.

    b. imhist():Display a histogram of image data.

    M.Sc. (Comp Sci) Part II 9

  • 8/3/2019 Dip Paper-1 Sec II

    10/47

    Digital Image Processing Paper I Section II

    Output:

    M.Sc. (Comp Sci) Part II 10

  • 8/3/2019 Dip Paper-1 Sec II

    11/47

    Digital Image Processing Paper I Section II

    Source code: (Image Averaging)

    figure;

    f = imread('saturn.tif');

    % D --> Noise DensityD = 0.02;

    g = imnoise(f,'salt & pepper',D);

    % n = imsubtract(f,g);

    subplot(1,2,1);

    imshow(g);

    title('Noisy Image g(x,y)=f(x,y) + n(x,y)');

    avg = filter2(fspecial('average',3),g)/300;

    subplot(1,2,2);

    imshow(avg);

    title('Averaging Filter Image');

    Functions used:

    a. imnoise(): J = imnoise(I,type) adds noise of given type to the intensity image I. type is a string

    that can have one of these values:

    'gaussian' for Gaussian white noise

    'localvar' for zero-mean Gaussian white noise with an intensity-dependent variance

    'poisson' for Poisson noise

    'salt & pepper' for "on and off" pixels 'speckle' for multiplicative noise

    b.

    filter2(h,X): filters the data in X with the two-dimensional FIR filter in the matrix h. It computesthe result, Y, using two-dimensional correlation, and returns the central part of the correlation that

    is the same size as X

    M.Sc. (Comp Sci) Part II 11

  • 8/3/2019 Dip Paper-1 Sec II

    12/47

    Digital Image Processing Paper I Section II

    Output: (Image Averaging)

    M.Sc. (Comp Sci) Part II 12

  • 8/3/2019 Dip Paper-1 Sec II

    13/47

    Digital Image Processing Paper I Section II

    Source code: (Smoothing)

    f = imread('flowers.tif');

    n = 10;

    Wn = 0.10;

    mask = fir1(n,Wn);

    % This creates a mask containing the coefficients of the

    % order n Hamming-windowed filter.

    % This is a lowpass, linear phase FIR filter with cutoff

    % frequency Wn.

    g = imfilter(f,mask);

    figure;

    subplot(1,2,1);

    imshow(f);

    title('Original Image');

    subplot(1,2,2);imshow(g);

    title('Smoothing Effect due to a given mask');

    Functions used:

    a. fir1 (n,Wn): fir1(n,Wn) returns row vector b containing the n+1 coefficients of an order n

    lowpass FIR filter. This is a Hamming-window based, linear-phase filter with normalized cutoff

    frequency Wn. The output filter coefficients, b, are ordered in descending powers of z. Wn is a

    number between 0 and 1, where 1 corresponds to the Nyquist frequency.

    b.

    imfilter(): filters the multidimensional array A with the multidimensional filter H. The array, A,can be a non-sparse numeric array of any class and dimension. The result, B, has the same size

    and class as A.

    M.Sc. (Comp Sci) Part II 13

  • 8/3/2019 Dip Paper-1 Sec II

    14/47

    Digital Image Processing Paper I Section II

    Output: (Smoothing)

    M.Sc. (Comp Sci) Part II 14

  • 8/3/2019 Dip Paper-1 Sec II

    15/47

    Digital Image Processing Paper I Section II

    Practical No. 2

    Image Enhancement in Frequency Domain

    Aim:A filter function from one of the following filters along with a set of values for the parameter list is

    provided. For this filter function derive a (k x k) filter mask for one of the values of k, k = 3, 5, 9. The

    filter mask is to be applied to the given input image and the enhanced image is to be displayed.

    (i) Gaussian Low Pass Filter

    (ii) Butterworth Low Pass Filter

    iii) Ideal High Pass Filter

    iv) Ideal Low Pass Filter

    Description:

    Image enhancement in the frequency domain is achieved by computing the Fourier transform of the

    image to be enhanced, multiplying the result by a filter (rather than convolve in the spatial domain), and

    take the inverse transform to produce the enhanced image. For instance, blurring of an image is achieved

    by reducing its high frequency components, or sharpening an image by increasing the magnitude of its

    high frequency components. However, computationally, it is often more efficient to implement these

    operations as convolutions by small spatial filters in the spatial domain. Low frequencies in the Fourier

    transform are responsible for the general gray-level appearance of an image over smooth areas while high

    frequencies are responsible for detail, such as edges and noise.

    i. Image Enhancement using Ideal Low Pass Filter: Ideal Lowpass filter is a filter that cuts off

    all high frequency components of the Fourier transform that are at a distance greater than a

    specified distance D0 from the origin of the transform.

    H (u, v) = 1 , if D (u, v) D0 OR

    = 0 , if D (u, v) > D0

    Where D0 is a specified nonnegative quantity and D (u, v) is the distance from point (u, v) to the

    origin of the frequency rectangle. The distance from any point (u, v) to the center (origin) of the

    Fourier transform is given by

    D (u, v) = [(u - M/2) 2 + (v N/2) 2]

    ii. Butterworth Low-pass filter: Butterworth Low-pass filter is a complex computational imagingfilter used to remove statistical noise and enhance image quality. It is applied in Fourier (or

    frequency) space (see Fourier transformation FT , Fourier filtering) to remove or supress

    unwanted high spatial frequencies from an image. Whereas real-space filters are applied byconvolution on the image, frequency space filters are applied to the Fourier transform of the

    image by point-by-point multiplication. A Butterworth filter is represented mathematically by the

    expression:

    H (u, v) = 1

    1 + [D (u, v) / D0]2n

    M.Sc. (Comp Sci) Part II 15

    http://www.medcyclopaedia.com/library/topics/volume_i/f/fourier_transformation_ft_.aspxhttp://www.medcyclopaedia.com/library/topics/volume_i/f/fourier_transformation_ft_.aspxhttp://www.medcyclopaedia.com/library/topics/volume_i/f/fourier_transformation_ft_.aspxhttp://www.medcyclopaedia.com/library/topics/volume_i/f/fourier_filtering.aspxhttp://www.medcyclopaedia.com/library/topics/volume_i/c/convolution.aspxhttp://www.medcyclopaedia.com/library/topics/volume_i/f/fourier_filtering.aspxhttp://www.medcyclopaedia.com/library/topics/volume_i/c/convolution.aspxhttp://www.medcyclopaedia.com/library/topics/volume_i/f/fourier_transformation_ft_.aspx
  • 8/3/2019 Dip Paper-1 Sec II

    16/47

    Digital Image Processing Paper I Section II

    where H (u, v) is the amplitude of the filter at a spatial frequency D (u, v). D 0 is the frequencythat controls the filter roll-off and 2n is the power factor, which together with D (u, v) determines

    the Butterworth filter shape. For large values of D (u, v), the filter is 'sharp' allowing high

    frequency noise and sharp edges through into the image. Smaller values of D (u, v) result in

    increasingly smooth images and reduced contrast edges. Unlike the Ideal Lowpass filter, the

    Butterworth Lowpass filter transfer function does not have a sharp discontinuity that establishes aclear cutoff between passed and filtered frequencies.

    iii. Gaussian Lowpass Filter: The form of Gaussian Lowpass filters in two dimensions is given by

    Hgauss[k,l] = exp|-a(( k - k0)2 + (l l0)

    2 )/D02

    where a and c are two parameters.

    At the cut-off frequency ((k k0)2 + (l l0)

    2 = D02) the magnitude is attenuated to exp (-a).

    Compared with the ideal filter, the Gaussian filter is smooth and it no longer have the undesirable

    ringing effect.

    iv. Ideal Highpass filter: Highpass filters give high values at edges, low values in constant regions.Adding high frequencies back into the image enhances edges. One approach can be :

    Image = Image + [Image smooth (Image)]

    A 2-D ideal highpass filter(IHPF) is defined as :

    H (u, v) = 0 if D (u, v) D0 OR

    1 if D (u, v) > D0

    Where D0 is the cutoff distance measured from the origin of the frequency rectangle, and D (u, v)

    is given by

    D (u, v) = [(u - M/2) 2 + (v N/2) 2]

    M.Sc. (Comp Sci) Part II 16

  • 8/3/2019 Dip Paper-1 Sec II

    17/47

    Digital Image Processing Paper I Section II

    Source code: (Ideal Low-pass filter)

    figure;

    subplot(2,2,1);

    f = imread('ngc4024m.tif');

    imshow(f);

    title('Original Image');

    n = 28;

    Wn = 0.02;

    H = fir1(n,Wn,'Low');

    g = imfilter(f,H);

    subplot(2,2,2);

    imshow(g);title('Ideal Low-pass Filtered Image');

    subplot(2,2,3);

    imhist(f);

    title('Histogram');

    subplot(2,2,4);

    imhist(g);

    title('Histogram of Ideal Low-Pass Filtered Image');

    Functions Used:

    a. fir1 (n, Wn, Low): fir1 (n, Wn) returns row vector b containing the n+1 coefficients of an order

    n lowpass FIR filter. This is a Hamming-window based, linear-phase filter with normalized cutoff

    frequency Wn. The output filter coefficients, b, are ordered in descending powers of z. Wn is a

    number between 0 and 1, where 1 corresponds to the Nyquist frequency.

    b. imfilter(A, H) : filters the multidimensional array A with the multidimensional filter H. The

    array, A, can be a nonsparse numeric array of any class and dimension. The result, B, has the

    same size and class as A.

    M.Sc. (Comp Sci) Part II 17

  • 8/3/2019 Dip Paper-1 Sec II

    18/47

    Digital Image Processing Paper I Section II

    Output: (Ideal Low-pass filter)

    M.Sc. (Comp Sci) Part II 18

  • 8/3/2019 Dip Paper-1 Sec II

    19/47

    Digital Image Processing Paper I Section II

    Source Code: (Butterworth Low-pass filter)

    figure;

    subplot(2,2,1);

    imshow(f);

    c_freq = 0.6;title('Original Image');

    H = butter(2,c_freq,'low');

    g = imfilter(f,H);

    subplot(2,2,2);

    imshow(g);

    title('Butterworth Low-pass Filtered Image');

    subplot(2,2,3);

    imhist(f);

    title('Histogram');

    subplot(2,2,4);imhist(g);title('Histogram of Butterworth Low-Pass Filtered Image');

    Functions Used:

    a. butter(n, Wn): butter(n,Wn) designs an order n lowpass digital Butterworth filter withnormalized cutoff frequency Wn. It returns the filter coefficients in length n+1 row vectors b and

    a, with coefficients in descending powers of z.

    b. imfilter(A, H): filters the multidimensional array A with the multidimensional filter H. The

    array, A, can be a non-sparse numeric array of any class and dimension. The result, B, has the

    same size and class as A.

    M.Sc. (Comp Sci) Part II 19

  • 8/3/2019 Dip Paper-1 Sec II

    20/47

    Digital Image Processing Paper I Section II

    Output: (Butterworth Low-pass filter)

    M.Sc. (Comp Sci) Part II 20

  • 8/3/2019 Dip Paper-1 Sec II

    21/47

    Digital Image Processing Paper I Section II

    SourceCode: (Gaussian Low Pass filter)

    f = imread('ngc4024m.tif'); % Input Image

    subplot(2,2,1);

    imshow(f);

    title('Original Image');

    hsize = 6; % No. of rows and columns in H

    sigma = 60; % Standard Deviation

    H = fspecial('gaussian',hsize,sigma);

    g = imfilter(f,H);

    subplot(2,2,2); imshow(g); title('Gaussian Low Pass Filtered Image');

    subplot(2,2,3); imhist(f); title('Histogram of an Input Image');

    subplot(2,2,4); imhist(g);

    title('Histogram of Gaussian Low Pass Filtered Image');

    Functions Used:

    a. fspecial('gaussian',hsize,sigma): returns a rotationally symmetric Gaussian lowpass filter of sizehsize with standard deviation sigma (positive). hsize can be a vector specifying the number ofrows and columns in h, or it can be a scalar, in which case h is a square matrix. The default value

    forhsize is [3 3]; the default value forsigma is 0.5.

    b. imfilter(A, H): filters the multidimensional array A with the multidimensional filter H. The

    array, A, can be a nonsparse numeric array of any class and dimension. The result, B, has thesame size and class as A.

    M.Sc. (Comp Sci) Part II 21

  • 8/3/2019 Dip Paper-1 Sec II

    22/47

    Digital Image Processing Paper I Section II

    Output: (Gaussian Low Pass filter)

    M.Sc. (Comp Sci) Part II 22

  • 8/3/2019 Dip Paper-1 Sec II

    23/47

    Digital Image Processing Paper I Section II

    Source code: (Ideal High-pass filter)

    figure;

    subplot(2,2,1);

    imshow(f);

    title('Original Image');

    n = 5;

    Wn = 0.3;

    H = fir1(n,Wn,'High');

    g = imfilter(f,H);

    subplot(2,2,2);

    imshow(g);

    title('Ideal High-pass Filtered Image');

    subplot(2,2,3);

    imhist(f);

    title('Histogram');

    subplot(2,2,4);

    imhist(g);

    title('Histogram of Ideal High-Pass Filtered Image');

    Functions Used:

    a. fir1(n, Wn, 'High'): Returns row vector b containing the n+1 coefficients of an order n highpassFIR filter. This is a Hamming-window based, linear-phase filter with normalized cutoff frequency

    Wn. The output filter coefficients, b, are ordered in descending powers of z. Wn is a numberbetween 0 and 1, where 1 corresponds to the Nyquist frequency.

    M.Sc. (Comp Sci) Part II 23

  • 8/3/2019 Dip Paper-1 Sec II

    24/47

    Digital Image Processing Paper I Section II

    Output:

    M.Sc. (Comp Sci) Part II 24

  • 8/3/2019 Dip Paper-1 Sec II

    25/47

    Digital Image Processing Paper I Section II

    Practical No. 3

    Image Enhancement Statistical Filters

    Aim:The Statistical Filter specifications are provided. This filter should be applied to the input image andthe resulting image should be displayed

    (i) Mean and Median Filters

    (ii) Max-min and Min-max Filters

    Description: Spatial filtering is the method of choice in situations when only additive noise is present.

    When the only degradation present in an image is noise,

    G(u, v) = F(u, v) + N(u, v)

    In the case of periodic noise, it usually is possible to estimate N (u, v) from the spectrum of G(u, v). In

    this case N(u, v) can be subtracted from G(u, v) to obtain an estimate of original image.

    a. Mean and Median Filters: These are basically neighborhood-averaging filters These replace thevalue of each pixel, a [i,j] say, by a weighted-average of the pixels in some neighborhood around

    it, i.e. a weighted sum ofa[i+p,j+q], withp = -k to k, q = -k to kfor some positive k; the weightsare non-negative with the highest weight on thep = q = 0 term. If all the weights are equal thenthis is a mean filter. One of the simplest Mean filters is Arithmetic Mean filter. Let Sxy representthe set of coordinates in a rectangular subimage window of size m x n centered at point (x, y).This filter computes the average value of the corrupted image g (x, y) in the area defined by

    Sxy.Median filters replace each pixel value by the median of its neighbors, i.e. the value such that

    50% of the values in the neighborhood are above, and 50% are below. This can be difficult and

    costly to implement due to the need for sorting of the values. However, this method is generally

    very good at preserving edges.

    Mean and median filters are smoothing filters. Arithmatic mean filter simply smoothes

    local variation in an image. Noise is reduced as a result of blurring.Meadian filters are quitepopular , because for certain types of random noise ,t hey provide excellent noise reduction

    capabilities, with considerably less blurring than linear smoothing filters of same size.

    b. Min and Max Filters: The median represents the 50th percentile of a ranked set of numbers.Using the 100th percentile results in max filter. This filter is useful for finding the brightest points

    in an image. Also, because proper noise has very low values, it is reduced by this filter as a result

    of the max selection process in the sub image area S xy. The 0th percentile filter is the min filter.

    This filter is useful for finding the darkest points in an image. Also, it reduces salt noise as a

    result of the min operation. MinMax filter works like difference filter, except that maximum and

    minimum pixel is searched. After calculating absolute difference from middle element, pixel

    having higher resulting value is stored as resulting pixel.

    M.Sc. (Comp Sci) Part II 25

  • 8/3/2019 Dip Paper-1 Sec II

    26/47

    Digital Image Processing Paper I Section II

    Source Code:(Mean Filter)

    % ================

    % Mean Filter

    % ================

    f = imread('trees.tif');

    subplot(2,2,1);

    imshow(f);

    title('Original Image');

    m = mean2(double(f));

    g = imfilter(f,m);

    k = imabsdiff(f,g);

    subplot(2,2,2);

    imshow(g);

    title('Mean Filtered Image');

    subplot(2,2,3);

    imshow(k);

    title('Absolute Difference of f and g');

    M.Sc. (Comp Sci) Part II 26

  • 8/3/2019 Dip Paper-1 Sec II

    27/47

    Digital Image Processing Paper I Section II

    Output:(Mean Filter)

    M.Sc. (Comp Sci) Part II 27

  • 8/3/2019 Dip Paper-1 Sec II

    28/47

    Digital Image Processing Paper I Section II

    Source Code: (Median Filter)

    figure;

    f = imread('trees.tif');

    g = imnoise(f,'salt & pepper',0.05);

    subplot(1,2,1);imshow(g);

    title('Input Image');

    %K = filter2(fspecial('average',3),g)/255;

    M = medfilt2(g,[3 3]);

    %figure, imshow(K)

    subplot(1,2,2);

    imshow(M);

    title('Median filtered image');

    M.Sc. (Comp Sci) Part II 28

  • 8/3/2019 Dip Paper-1 Sec II

    29/47

    Digital Image Processing Paper I Section II

    Output: (Median Filter)

    M.Sc. (Comp Sci) Part II 29

  • 8/3/2019 Dip Paper-1 Sec II

    30/47

    Digital Image Processing Paper I Section II

    Source Code: (Mini-Max Filter)

    figure;

    f = imread('trees.tif');

    g = imnoise(f,'salt & pepper',0.1);

    subplot(1,2,1);

    imshow(g);

    title('Original Image');

    n = 5; % Filter order

    freq = [0 0.4 0.5 1]; % Frequency band edges

    a = [1 1 0 0]; % Desired amplitudes

    b = remez(n,freq,a);

    L = imfilter(f,b);

    subplot(1,2,2);imshow(L);

    title('Mini-max Filtered Image');

    Functions Used:

    a. remez (n,freq,a): remez (n, freq, a) returns row vector b containing the n+1 coefficients of theorder n FIR filter whose frequency-amplitude characteristics match those given by vectors f and

    a.

    b. imfilter(A, H) : filters the multidimensional array A with the multidimensional filter H (remezfilter). The array, A, can be a nonsparse numeric array of any class and dimension. The result, B,

    has the same size and class as A.

    M.Sc. (Comp Sci) Part II 30

  • 8/3/2019 Dip Paper-1 Sec II

    31/47

    Digital Image Processing Paper I Section II

    Output: (Mini-max filter)

    M.Sc. (Comp Sci) Part II 31

  • 8/3/2019 Dip Paper-1 Sec II

    32/47

    Digital Image Processing Paper I Section II

    Practical No. 4

    Lossy Image Compression

    Aim: An input image is provided. A Lossy Image Compression algorithm is provided. The algorithm is to

    be applied the input image and percentage reduction along with the compressed image is to be displayed.

    This image is now to be decompressed and the original image must be displayed.

    Description:

    A lossy compression method is one where compressing data and then decompressing it retrieves

    data that may well be different from the original, but is close enough to be useful in some way. Lossy

    compression is most commonly used to compress multimedia data (audio, video, still images), especially

    in applications such as streaming media and internet telephony. By contrast, lossless compression is

    required for text and data files, such as bank records, text articles, etc.

    Lossy compression formats suffer from generation loss: repeatedly compressing and decompressing the

    file will cause it to progressively lose quality. This is in contrast with lossless data compression.

    Lossy coding is based on the concept of compromising the accuracy of the reconstructed image inexchange for increased compression. If the resulting destoration can be tolerated, the increase in

    compression can be significant. In fact, many loosing techniques are capable of reproducing recognizable

    monochrome images from data that have been compressed by more than 100:1 and images that are

    virtually indistinguishable from the original at 10:1 to 50:1. Error free encoding of monochrome images ,

    however seldom results in more than a 3:1 reduction in data.

    M.Sc. (Comp Sci) Part II 32

    http://en.wikipedia.org/wiki/Data_compressionhttp://en.wikipedia.org/wiki/Multimediahttp://en.wikipedia.org/wiki/Sound_recording_and_reproductionhttp://en.wikipedia.org/wiki/Videohttp://en.wikipedia.org/wiki/Imagehttp://en.wikipedia.org/wiki/Streaming_mediahttp://en.wikipedia.org/wiki/VOIPhttp://en.wikipedia.org/wiki/Lossless_compressionhttp://en.wikipedia.org/wiki/Generation_losshttp://en.wikipedia.org/wiki/Lossless_data_compressionhttp://en.wikipedia.org/wiki/Data_compressionhttp://en.wikipedia.org/wiki/Multimediahttp://en.wikipedia.org/wiki/Sound_recording_and_reproductionhttp://en.wikipedia.org/wiki/Videohttp://en.wikipedia.org/wiki/Imagehttp://en.wikipedia.org/wiki/Streaming_mediahttp://en.wikipedia.org/wiki/VOIPhttp://en.wikipedia.org/wiki/Lossless_compressionhttp://en.wikipedia.org/wiki/Generation_losshttp://en.wikipedia.org/wiki/Lossless_data_compression
  • 8/3/2019 Dip Paper-1 Sec II

    33/47

    Digital Image Processing Paper I Section II

    Source Code:

    % Practical No. 4 ... Lossy Image Compression using DCT

    % Lossy Image Compression

    I = imread('cameraman.tif');I = im2double(I);

    T = dctmtx(10);

    B = blkproc(I,[10 10],'P1*x*P2',T,T');mask = [1 1 1 1 0 0 0 0 0 0

    1 1 1 0 0 0 0 0 0 0

    1 1 0 0 0 0 0 0 0 01 0 0 0 0 0 0 0 0 0

    0 0 0 0 0 0 0 0 0 0

    0 0 0 0 0 0 0 0 0 0

    0 0 0 0 0 0 0 0 0 0

    0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0

    0 0 0 0 0 0 0 0 0 0];B2 = blkproc(B,[10 10],'P1.*x',mask);

    I2 = blkproc(B2,[10 10],'P1*x*P2',T',T);

    imshow(I), figure, imshow(I2)

    M.Sc. (Comp Sci) Part II 33

  • 8/3/2019 Dip Paper-1 Sec II

    34/47

    Digital Image Processing Paper I Section II

    Output:

    Original Image DCT compressed Image

    M.Sc. (Comp Sci) Part II 34

  • 8/3/2019 Dip Paper-1 Sec II

    35/47

    Digital Image Processing Paper I Section II

    Practical No. 5

    Image Segmentation

    Aim: To write a program to input an image and perform image segmentation to extract individual objects

    from that image.Pressed image is to be displayed. The nature of information lost is to be explained. Thisimage is to be decompressed and the original image must be displayed.

    Description:

    Segmentation subdivides an image into its constituent regions or objects. The level to which the

    subdivision is carried depends on the problem being solved. That is, segmentation should stop when the

    objects of interest in an application have been isolated. There is no point in carrying segmentation past the

    level of detail required to identify those elements. Segmentation accuracy determines the eventual successor failure of computerized analysis procedures. Image algorithms generally are based on one of two basic

    properties of intensity values: discontinuity and similarity. In the first category, the approach is to

    partition an image based on abrupt changes in intensity, such as edges in an image. The principal

    approaches in the second category are based on partitioning an image into regions that are similar

    adco0rding to a set of predefined criteria. Thresholding, region growing, and region splitting and mergingare example of methods in this category.

    Functions Used:

    a. rgb2gray(I): rgb2gray converts RGB images to grayscale by eliminating the hue andsaturation information while retaining the luminance. I = rgb2gray(RGB) converts the

    truecolor image RGB to the grayscale intensity image I.

    b. medfilt2(A, [m n]):B = medfilt2(A,[m n]) performs median filtering of the matrix A in twodimensions. Each output pixel contains the median value in the m-by-n neighborhood aroundthe corresponding pixel in the input image. medfilt2 pads the image with zeros on the edges,

    so the median values for the points within [m n]/2 of the edges may appear distorted.

    c. edge(I,method): edge takes an intensity image I as its input, and returns a binary imageBW of the same size as I, with 1's where the function finds edges in I and 0's elsewhere.

    method is a parameter which represents the method used for edge-finding.

    d. conv2(A,B): C = conv2(A,B) computes the two-dimensional convolution of matrices A andB. If one of these matrices describes a two-dimensional finite impulse response (FIR) filter,

    the other matrix is filtered in two dimensions. The size of C in each dimension is equal to the

    sum of the corresponding dimensions of the input matrices, minus one. That is, if the size of

    A is [ma,na] and the size of B is [mb,nb], then the size of C is [ma+mb-1,na+nb-1].

    M.Sc. (Comp Sci) Part II 35

  • 8/3/2019 Dip Paper-1 Sec II

    36/47

    Digital Image Processing Paper I Section II

    Source code:

    % This is a program for extracting objects from an image.

    % Written for vehicle number plate segmentation and extraction

    % E.g. for "Car.jpg". There will be mx connected components.Here one can give a % value between 1 and mx for

    % or in a loop you can extract all connected components% If you are using the attached car image,

    % by giving 17,18,20,23,27,29 to L you can extract the number plate completely.

    clc;clear all;close all;

    im=imread('I1.jpg');

    im1=rgb2gray(im); % RGB2GRAY --> Convert RGB image or colormap to grayscale.

    im2=medfilt2(im1,[3 3]); % MEDFILT2 --> Perform 2-D median filtering. Median filtering the image to re

    noise

    BW = edge(im2,'sobel'); % EDGE --> Find edges in intensity image.

    [imx,imy]=size(BW); % Dimensions

    msk=[0 0 0 0 0; % Mask

    0 1 1 1 0;

    0 1 1 1 0;

    0 1 1 1 0;

    0 0 0 0 0;];

    B=conv2(BW,msk); % CONV2 Two dimensional convolution. Smoothing image

    % to reduce the number of connected components

    L = bwlabel(B,8); % BWLABEL --> Calculating connected components

    mx=max(max(L));

    [r,c] = find(L==1); % FIND --> Find indices of nonzero elements.

    rc = [r c];

    [sx sy]=size(rc);

    n1=zeros(imx,imy); % zeros --> Zeros array

    for i=1:sx

    x1=rc(i,1);

    y1=rc(i,2);

    n1(x1,y1)=100; % Storing the extracted image in an array

    end

    figure('Name','Input Image'),imshow(im);

    figure('Name','Gray Image'),imshow(im1);

    figure('Name','Median Filtered Image (Noise Removal)'),imshow(im2);

    figure('Name','Smoothing Image'),imshow(B);

    figure('Name','Extracted Image'),imshow(n1,[]);

    M.Sc. (Comp Sci) Part II 36

  • 8/3/2019 Dip Paper-1 Sec II

    37/47

    Digital Image Processing Paper I Section II

    Output:

    Input Image Gray Image

    Median Filtered Image (Noise Removal)

    M.Sc. (Comp Sci) Part II 37

  • 8/3/2019 Dip Paper-1 Sec II

    38/47

    Digital Image Processing Paper I Section II

    Smoothing Image Extracted Image

    M.Sc. (Comp Sci) Part II 38

  • 8/3/2019 Dip Paper-1 Sec II

    39/47

    Digital Image Processing Paper I Section II

    Practical No. 6

    Region Filling

    Aim: Write a program to input an image and fill the empty region inside the image using Region Filling

    procedure.

    Description:

    Region Filling is based on set dilations, complementation and intersections.

    Region Filling Algorithm

    Binary Region Filling

    Beginning with a point p inside of a boundary, fill the entire region with 1s

    Grayscale Region Filling

    Beginning with a point p inside of a boundary, fill the entire region with the mean value of the region.

    Region Filling Definition

    Region filling is based on a set of dilations, complementation, and intersections.

    Xk= (Xk-1 XOR B) c for k 1,2n

    Where (Xk-1 XOR B) is a dilation

    B is the structuring element

    c is the complement of the image

    Complementation, Dilation, Intersection

    1. Complement the original image

    2. Start at a location inside of a boundary

    3. Dilate the pixel with the structuring element

    4. Keep all pixels that intersect with the complement of that image

    5. Repeat from 3 until entire region is filled

    Functions Used:

    a. Imagesc(A): The imagesc function scales image data to the full range of the current colormapand displays the image.

    b. Dilate(x,B): BW2 = dilate(BW1,SE) performs dilation on the binary image BW1, using thebinary structuring element SE. SE is a matrix containing only 1's and 0's.

    c. Sum(A): sum(A) returns sums along different dimensions of an array.

    M.Sc. (Comp Sci) Part II 39

  • 8/3/2019 Dip Paper-1 Sec II

    40/47

    Digital Image Processing Paper I Section II

    Source Code:

    % region filling

    clc;close all;clear all;

    % Input

    A=[0 0 0 0 0 0 00 0 1 1 0 0 0

    0 1 0 0 1 0 0

    0 1 0 0 1 0 0

    0 0 1 0 1 0 0

    0 0 1 0 1 0 0

    0 1 0 0 0 1 0

    0 1 0 0 0 1 0

    0 1 1 1 1 0 0

    0 0 0 0 0 0 0];

    figure(1),clf,colormap('gray') % CLF --> Clear current figure

    subplot(1,3,1),imagesc(A); % IMAGESC --> Scale data and display as image.Ac = ones(size(A)) - A; % Ac --> A's complementB = [0 1 0; 1 1 1; 0 1 0]; % Restructuring Element

    x = zeros(size(A));

    x(3,3)=1; % Start Point

    k=0;

    flag_region_found = 0;

    while flag_region_found ~= 1,

    k = k+1;

    subplot(1,3,2),imagesc(x);

    xnew = and(dilate(x,B),Ac); % DILATE --> Perform dilation on binary image.

    if sum(sum(xnew-x))== 0,

    flag_region_found = 1;

    elsex=xnew;

    end

    pause(.6)

    endy = x+A;

    subplot(1,3,3),imagesc(y);

    M.Sc. (Comp Sci) Part II 40

  • 8/3/2019 Dip Paper-1 Sec II

    41/47

    Digital Image Processing Paper I Section II

    Output:

    Original Image Filled Region Original + Filled Region

    M.Sc. (Comp Sci) Part II 41

  • 8/3/2019 Dip Paper-1 Sec II

    42/47

    Digital Image Processing Paper I Section II

    Practical No. 7

    Morphological Operations

    Aim:To write a program to input an image and to perform following morphological operations on it:

    1. Erosion and Dilation

    2. Opening and Closing

    3. Boundary Extraction

    Description:

    Erosion and Dilation: Erosion and dilation are two basic operators in mathematical morphology. The

    basic effect of erosion operator on a binary image is to erode away the boundaries of foreground pixels

    (usually the white pixels). Thus areas of foreground pixels shrink in size, and "holes" within those areas

    become larger.

    The dilation is the other of the two basic operators in mathematical morphology, the first one being

    erosion. The basic effect of dilation on binary images is to enlarge the areas of foreground pixels (i.e.

    white pixels) at their borders. The areas of foreground pixels thus grow in size, while the background

    "holes" within them shrink.

    Opening and Closing: The opening is a composite operator, constructed from the two basic operators

    described above. Opening of set A by set B is achieved by first the eroding set A by B, then dilating the

    resulting set by B.

    The closing, like opening, is also a composite operator. The closing of set A by set B is achieved by first

    dilating of set A by B, then eroding the resulting set by B.

    Boundary Extraction: The boundary of set A can be found by first eroding A by B, then taking the set

    difference between the original A and the eroded A.

    M.Sc. (Comp Sci) Part II 42

    http://www.inf.u-szeged.hu/~ssip/1996/morpho/morphology.html#bin-erode%23bin-erodehttp://www.inf.u-szeged.hu/~ssip/1996/morpho/morphology.html#bin-erode%23bin-erodehttp://www.inf.u-szeged.hu/~ssip/1996/morpho/morphology.html#bin-erode%23bin-erode
  • 8/3/2019 Dip Paper-1 Sec II

    43/47

    Digital Image Processing Paper I Section II

    Functions Used:

    a. imdilate(IM,SE): IM2 = imdilate(IM,SE) dilates the grayscale, binary, or packed binary imageIM, returning the dilated image, IM2. The argument SE is a structuring element object, or array

    of structuring element objects, returned by the strel function. If IM is logical and the structuring

    element is flat, imdilate performs binary dilation; otherwise, it performs grayscale dilation. If SE

    is an array of structuring element objects, imdilate performs multiple dilations of the input image,

    using each structuring element in SE in succession.

    b. imerode(IM,Se):IM2 = imerode(IM,SE) erodes the grayscale, binary, or packed binary imageIM, returning the eroded image, IM2. The argument SE is a structuring element object, or array

    of structuring element objects, returned by the strel function. If IM is logical and the structuring

    element is flat, imerode performs binary dilation; otherwise it performs grayscale erosion. If SE is

    an array of structuring element objects, imerode performs multiple erosions of the input image,

    using each structuring element in SE in succession.

    c. imopen(IM,SE): IM2 = imopen(IM,SE) performs morphological opening on the grayscale orbinary image IM with the structuring element SE. The argument SE must be a single structuring

    element object, as opposed to an array of objects.

    d. imclose(IM,SE): IM2 = imclose(IM,SE) performs morphological closing on the grayscale orbinary image IM, returning the closed image, IM2. The structuring element, SE, must be a single

    structuring element object, as opposed to an array of objects.

    M.Sc. (Comp Sci) Part II 43

  • 8/3/2019 Dip Paper-1 Sec II

    44/47

    Digital Image Processing Paper I Section II

    Source Code:

    load p64int.txt; % 64 x 64 gray scale image

    V=[80:168];

    x=ones(size(p64int))-ismember(p64int,V);

    figure(1),clf,

    subplot(231),imagesc(x),colormap('gray')

    % dilation and erosion

    disp('0 - square (default)');

    disp('1 - circle');

    disp('2 - lower triangle');

    chos=input('Enter your structure element choice: ');

    if isempty(chos), chos=0; end

    switch chos

    case 0 % rectangle structure element

    dimen=input('enter dimension of the rectangle structure element (default 3): ');

    if isempty(dimen), dimen=3; end

    S=ones(dimen);case 1 % circle element

    r=input('enter radius of the circle structure element (default = 2): ');

    if isempty(r), r=2; end

    S=zeros(2*r+1); % a square of 2r+1for i=1:2*r+1,

    for j=1:2*r+1,

    if (i-r-1)^2+(j-r-1)^2

  • 8/3/2019 Dip Paper-1 Sec II

    45/47

    Digital Image Processing Paper I Section II

    Output (1):

    ***********************************0 - square (default)

    1 - circle2 - lower triangleEnter your structure element choice: 2

    Dilation and ErosionOpening and Closing

    M.Sc. (Comp Sci) Part II 45

  • 8/3/2019 Dip Paper-1 Sec II

    46/47

    Digital Image Processing Paper I Section II

    Output (2):

    ***********************************

    0 - square (default)1 - circle2 - lower triangleEnter your structure element choice: 1

    enter radius of the circle structure element (default = 2): 2Dilation and ErosionOpening and Closing

    M.Sc. (Comp Sci) Part II 46

  • 8/3/2019 Dip Paper-1 Sec II

    47/47

    Digital Image Processing Paper I Section II

    Output: (3).

    ***********************************

    0 - square (default)1 - circle2 - lower triangleEnter your structure element choice: 0

    enter dimension of the rectangle structure element (default 3): 3Dilation and ErosionOpening and Closing