0% found this document useful (0 votes)
226 views22 pages

DIP Programs

The document discusses converting a grayscale image to a binary image using hard thresholding. It involves: 1. Reading a grayscale image and converting it to double format if it is RGB. 2. Calculating the total sum of pixel values and dividing by total number of pixels to determine the threshold value. 3. Comparing each pixel value to the threshold - if the pixel value is greater than or equal to the threshold, it is set to 1, otherwise it is set to 0 to generate the binary image. The threshold can be varied to observe the effect on the resulting binary image.

Uploaded by

Sajag Chauhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
226 views22 pages

DIP Programs

The document discusses converting a grayscale image to a binary image using hard thresholding. It involves: 1. Reading a grayscale image and converting it to double format if it is RGB. 2. Calculating the total sum of pixel values and dividing by total number of pixels to determine the threshold value. 3. Comparing each pixel value to the threshold - if the pixel value is greater than or equal to the threshold, it is set to 1, otherwise it is set to 0 to generate the binary image. The threshold can be varied to observe the effect on the resulting binary image.

Uploaded by

Sajag Chauhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 22

1.

Perform the program for Contrast Stretching of an image


Explaination:
Contrast stretching (often called normalization) is a simple image enhancement
technique that attempts to improve the contrast in an image by `stretching' the
range of intensity values it contains to span a desired range of values, e.g. the
the full range of pixel values that the image type concerned allows. (Most
implementations accept a graylevel image as input and produce another
graylevel image as output.)
Before the stretching can be performed it is necessary to specify the upper and
lower pixel value limits over which the image is to be normalized. Often these
limits will just be the minimum and maximum pixel values that the image type
concerned allows. For example for 8-bit graylevel images the lower and upper
limits might be 0 and 255. Call the lower and the upper
limits a and b respectively.
The simplest sort of normalization then scans the image to find the lowest and
highest pixel values currently present in the image. Call these c and d. Then
each pixel P is scaled using the following function:

Values below 0 are set to 0 and values about 255 are set to 255
Code:

clear all;
close all;
clc;
%% Reading an image
a=imread('cameraman.tif');
a=double(a);
s=size(a);
%% Defingin points and calculating equation parameters
p1=[0,0];
p2=[150,20];
p3=[200,200];
p4=[255,255];
m1=(p1(1,2)-p2(1,2))/(p1(1,1)-p2(1,1));
m2=(p2(1,2)-p3(1,2))/(p2(1,1)-p3(1,1));
m3=(p3(1,2)-p4(1,2))/(p3(1,1)-p4(1,1));
c1=p1(1,2)-m1*p1(1,1);
c2=p2(1,2)-m2*p2(1,1);
c3=p3(1,2)-m3*p3(1,1);
%% Transformation function
t=[];
for x=0:255
    if(x<=p2(1,1))
        t=[t (m1*x+c1)];
    end
    if(x>p2(1,1) && x<=p3(1,1))
        t=[t (m2*x+c2)];
    end
    if(x>p3(1,1) && x<=p4(1,1))
        t=[t (m3*x+c3)];
    end
end
%% Getting output image
for n=1:s(1,1)
    for m=1:s(1,2)
        ot(n,m)=t(a(n,m)+1);
    end
end
plot(t)
grid on;
xlabel('Intensity in input image');
ylabel('Intensity in output image')
title('Piece-wise linear transformation : Contrast stretching function')
figure()
subplot(1,2,1)
imshow(a/255)
title('Original image')
subplot(1,2,2)
imshow(ot./255)     
title('Contrast stretching')
2. Zooming by interpolation and replication
Explaination:
It is also known as Nearest neighbor interpolation. As its name suggest, in this method,
we just replicate the neighboring pixels. As we have already discussed in the tutorial of
Sampling, that zooming is nothing but increase amount of sample or pixels. This
algorithm works on the same principle.

Working:
In this method we create new pixels form the already given pixels. Each pixel is
replicated in this method n times row wise and column wise and you got a zoomed
image. Its as simple as that.

For example:
if you have an image of 2 rows and 2 columns and you want to zoom it twice or 2 times
using pixel replication, here how it can be done.
For a better understanding, the image has been taken in the form of matrix with the pixel values
of the image.

1 2

3 4

The above image has two rows and two columns, we will first zoom it row wise.

Row wise zooming:


When we zoom it row wise, we will just simple copy the rows pixels to its adjacent new
cell.
Here how it would be done.

1 1 2 2

3 3 4 4

As you can that in the above matrix, each pixel is replicated twice in the rows.
Column size zooming:
The next step is to replicate each of the pixel column wise, that we will simply copy the
column pixel to its adjacent new column or simply below it.
Here how it would be done.

1 1 2 2

1 1 2 2

3 3 4 4

3 3 4 4

New image size:


As it can be seen from the above example, that an original image of 2 rows and 2
columns has been converted into 4 rows and 4 columns after zooming. That means the
new image has a dimensions of
(Original image rows * zooming factor, Original Image cols * zooming factor)

Code:

% Zooming

f1=input('Enter the factor by which the image is to be Zoomed: ');


s2=s*f1;
k=1;
l=1;
for (i=1:f1:s2)
for( j=1:f1:s2)
C(i,j)= A(k,l);
l=l+1;
end
l=1;
k=k+1;
end
for (i=1:f1:s2)
for (j=2:f1:s2-1)
C(i,j)= [C(i,j-1)+ C(i, j+1)]*0.5;
end
end
for(j=1:f1:s2)
for(i=2:f1:s2-1)
C(i,j)=[C(i-1,j)+C(i+1,j)]*0.5;
end
end
for (i=2:f1:s2-1)
for (j=2:f1:s2-1)
C(i,j)= [C(i,j-1)+ C(i, j+1)]*0.5;
end
end
figure,imshow(C)
title('Zoomed Image')
2. Read an image and perform histogram equalization of the input image and analyze the result

Explaination:
Histogram equalization is used to enhance contrast. It is not necessary that contrast
will always be increase in this. There may be some cases were histogram equalization
can be worse. In that cases the contrast is decreased.
Lets start histogram equalization by taking this image below as a simple image.
Image

Histogram of this image


The histogram of this image has been shown below.
Now we will perform histogram equalization to it.

PMF
First we have to calculate the PMF (probability mass function) of all the pixels in this
image. If you donot know how to calculate PMF, please visit our tutorial of PMF
calculation.

CDF
Our next step involves calculation of CDF (cumulative distributive function). Again if
you donot know how to calculate CDF , please visit our tutorial of CDF calculation.

Calculate CDF according to gray levels


Lets for instance consider this , that the CDF calculated in the second step looks like this.

Gray Level Value CDF

0 0.11

1 0.22
2 0.55

3 0.66

4 0.77

5 0.88

6 0.99

7 1

Then in this step you will multiply the CDF value with (Gray levels (minus) 1) .
Considering we have an 3 bpp image. Then number of levels we have are 8. And 1 subtracts 8 is
7. So we multiply CDF by 7. Here what we got after multiplying.

Gray Level Value CDF CDF * (Levels-1)

0 0.11 0

1 0.22 1

2 0.55 3

3 0.66 4

4 0.77 5

5 0.88 6

6 0.99 6
7 1 7

Now we have is the last step, in which we have to map the new gray level values into
number of pixels.
Lets assume our old gray levels values has these number of pixels.

Gray Level Value Frequency

0 2

1 4

2 6

3 8

4 10

5 12

6 14

7 16

Now if we map our new values to , then this is what we got.

Gray Level Value New Gray Level Value Frequency

0 0 2

1 1 4
2 3 6

3 4 8

4 5 10

5 6 12

6 6 14

7 7 16

Now map these new values you are onto histogram, and you are done.
Lets apply this technique to our original image. After applying we got the following
image and its following histogram.

Histogram Equalization Image


Cumulative Distributive function of this image

Histogram Equalization histogram


Comparing both the histograms and images
Code:
% Program to obtain histogram equalization concept
I=imread('trees.tif');
J=imcomplement(I);
imhist(J,100);
imshow(I);
title('original');
figure,imshow(J);
title('complement');
I=histeq(I);
figure,imhist(I,64);
title('equilized');
figure,imhist(J,64);
title('histogram');
n=numel(I);
p=imhist(I)/n;
figure,plot(p);
title('normalized');
K=imadjust(I,[0;1],[0.4;1],0.5);
figure,imshow(K);
title('adjusted image');
T=maketform('affine',[.3 0 0;.5 1 0;0 1 1]);
tformfwd([0,0],T);
I2=imtransform(I,T);
figure,imshow(I2);
title('forward image');
5. Read a grayscale image and convert it into a binary image using hard thresholding. Make the
threshold value as a user defined parameter vary the threshold and observe the result.
function [binary] = convert2binary(img) 
   
     [x, y, z]=size(img);
   
     % if Read Image is an RGB Image then convert 
     % it to a Gray Scale Image For an RGB image 
     % the value of z will be 3 and for a Grayscale
     % Image the value of z will be 1
   
    if z==3
         img=rgb2gray(img);
    end
   
    % change the class of image 
    % array from 'unit8' to 'double'
    img=double(img);
   
    % Calculate sum of all the gray level
    % pixel's value of the GraySacle Image
    sum=0;
    for i=1:x
         for j=1:y
        sum=sum+img(i, j);
     end
     end
   
    % Calculate Threshold value by dividing the 
    % calculated sum by total number of pixels 
    % total number of pixels = rows*columns (i.e x*y) 
    threshold=sum/(x*y);
    
    % Create a image array having same number
    % of rows and column as Original image
    % with all elements as 0 (Zero).
    binary=zeros(x, y);
   
    % iterate over all the pixels of Grayscale 
    % Image and Assign 1 to binary(i, j), if gray
    % level value is >=  threshold value     
    % else assign 0 to binary(i, j) .
   
    for i=1:x
     for j=1:y
        if img(i, j) >= threshold
                binary(i, j) = 1;
        else
            binary(i, j)=0;
        end
     end
    end
end
   
   
% driver function 
   
% Read the target Image
img=imread('apple.png');
   
% Call convert2binary() function to convert
% Image to binary using thresholding
binary_image=convert2binary(img);
   
% Display result
imshow(binary_image);
6. Program to performs gray level slicing with background
% Image Enhancement in the Spatial Domain
% Grey level slicing with background
clc, clear all, close all;
p=imread(‘cameraman.tif’);
z=double(p);
[row col]=size(p);
for i=1:1:row
for j=1:1:col
if(z(i,j)>50)&&(z(i,j)<150)
z(i,j)=255;
else
z(i,j)=p(i,j);
end
end
end
subplot(1,2,1);
imshow(p);
title('Original Image');
subplot(1,2,2);

imshow(uint8(z));
title('Grey level slicing with background');
7. Program to performs gray level slicing without background
% Image

Enhancement in the Spatial Domain


% Grey level slicing without background
clc, clear all, close all;
p=imread(‘cameraman.tif’);
z=double(p);
[row col]=size(z);
for i=1:1:row
for j=1:1:col
if(z(i,j)>50)&&(z(i,j)<150)
z(i,j)=255;
else
z(i,j)=0;
end
end
end
subplot(1,2,1);
imshow(p);
title(‘Original Image’);
subplot(1,2,2);
imshow(uint8(z));
title(‘Grey level slicing without background’);
8. Image Negative – Image Enhancement in the Spatial Domain
% Image Enhancement in the Spatial Domain
% Image Negative
clc;
clear all;
close all;
i=imread(‘cameraman.tif’);
a=double(i);
c=255;
b=c-a;
figure(1);
colormap(gray);
imagesc(a);
title(‘Original Image’);
figure(2);
colormap(gray);
imagesc(b);
title(‘Negative Image’);
9. Program to performs logarithmic transformation

clc; clear all; close all;


f=imread('scene.jpg');
g=rgb2gray(f);
c=input('Enter the constant value, c = ');
[M,N]=size(g);
for x = 1:M
for y = 1:N
m=double(g(x,y));
z(x,y)=c.*log10(1+m); %#ok<AGROW>
end
end
imshow(f), figure, imshow(z);
10. Read an image and apply an normal averaging filter of size 3X3 and 5X5 to the image
function [filtered_img] = average_filter(noisy_img)
[m,n] = size(noisy_img);
filtered_img = zeros(m,n);
for i = 1:m-2
for j = 1:n-2
sum = 0;
for k = i:i+2
for l = j:j+2
sum = sum+noisy_img(k,l);
end
end
filtered_img(i+1,j+1) = sum/9.0;
end
end
end
img=imread('img.bmp');
filtered = average_filter(img);
imshow(uint8(filtered));
11. Weighted Filtering:
% Read Image for Noise Addition
img=imread('lena.bmp');
% Add Noise
Noi_img = imnoise(img,'salt & pepper', 0.02);
% Mask Definition
f=1/16*[1,2,1;2,4,2;1,2,1];
% Apply filter2 function
de_noi=filter2(f,Noi_img);
figure;
subplot(1,3,1);imshow(img);title('Original image')
subplot(1,3,2);imshow(Noi_img);title('Noisy image')
subplot(1,3,3);imshow(uint8(de_noi));title('Denoised image')
12. Median Filtering:
% Read Image for Noise Addition
img=imread('lena.bmp');
% Add Noise
Noi_img = imnoise(img,'salt & pepper', 0.02);
% Apply medfilt2 function
de_noi=medfilt2(Noi_img,[3 3]);
figure;
subplot(1,3,1);imshow(img);title('Original image')
subplot(1,3,2);imshow(Noi_img);title('Noisy image')
subplot(1,3,3);imshow(uint8(de_noi));title('Denoised image')

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy