You are on page 1of 36

DIGITAL IMAGE PROCESSING LAB.

University of Engineering and Management, Jaipur

NAME – NANDAN KARMAKAR


ENROLLMENT NO: 12017002001135
ROLL NO: 31
BATCH: 2017-21
YEAR : 4TH YEAR
8TH SEMESTER
EXPERIMENT NO: 1
AIM: Program to enhance image using image arithmetic and logical
operations.
THEORY: Bitwise logical operations can be performed between pixels of one or more than
oneimage.
1. AND/NAND Logical operations can be used for following applications:

1) Compute intersection of the images

2) Design of filter masks

3) Slicing of gray scale images

2. OR/NOR logical operations can be used for following applications:

1) Merging of two images

3. XOR/XNOR operations can be used for following applications:

1) To detect change in gray level in the image

2) Check similarity of two images

4. NOT operation is used for:

1) To obtain negative image

2) Making some features clear

MATLAB CODE:
clc
clear all
close all
a = imread('cameraman.tif');
b = imread('football.jpg');
c = rgb2gray(b);
d = imresize(c,[ 256 256]);
w= im2bw(a);
y= im2bw(d);
r = not(w);
e= and(w,y);
f= or(w,y);
s = xor(w,y);
imshow(e)
figure,imshow(f)
figure,imshow(s)

OUTPUT:
EXPERIMENT NO: 2
Aim: Program for an image enhancement using pixel operation.
1.Negative Image
2.Flip Image
3.Threshold Operaton
4.Contrast Stretching
Negative Image:
Threshold Operation:
EXPERIMENT NO: 3
AIM: Program for gray level slicing with and without background.
THEORY: Image enhancement can be done in two domain: Spatial Domain and Transform
domain. In spatial domain Image processing, there are two ways:
_ Point processing (Single pixel is processed at a time)

_ Neighborhood processing (Mask processing) Convolution of 3x3 or 5x5 or other size of mask

with image

In point processing, Grey level transformation can be given by following equation

g(x, y) = T(f(x, y)) → s = T(r)

Where, f(x, y) is original image, g(x, y) is transformed image, s = gray level of transformed

image,

r = gray level of original image.

Threshold operation: In threshold operation, Pixel value greater than threshold value is made

white and pixel value less than threshold value is made black.

s = 0ifr ≤ m

s = 255ifr > m

Where m = threshold

Thresholding Scan any document and use this method to make it clean

SLICING MATLAB CODE:

clc;
clear all;
close all;
a = imread('football.jpg');
% for better idea of matlab images, "help imdemos" in command window.
% converting the above color image into a gray level image
b = rgb2gray(a);

[m,n] = size(b);
% analyzing the above gray level image histogram using "imhist"
imshow(b); title('input image in gray level');
figure;
imhist(b);title('histogram of the input image at gray level');
% using matlab command "zeros"
c = zeros(m,n);
% initialing the for loop
for i = 1:m
for j = 1:n
% use the condition
if b(i,j) >= 227 % try with defferent intensity levels in the range from 227 to
245 for better understanding
c(i,j) = 255;
else
% c(i,j) = 0; % for without bachground
c(i,j) = b(i,j); % for with background
end
end
end

figure;
imshow(c);title('gray level sliced image from an intensity level 240 onwards');
SLICING OUTPUT:
BIT SLICING MATLAB CODE:
clc;

% reading image's pixel in c


c = imread('cameraman.tif');

% storing image information in cd


cd = double(c);

% extracting all bit one by one


% from 1st to 8th in variable
% from c1 to c8 respectively
c1 = mod(cd, 2);
c2 = mod(floor(cd/2), 2);
c3 = mod(floor(cd/4), 2);
c4 = mod(floor(cd/8), 2);
c5 = mod(floor(cd/16), 2);
c6 = mod(floor(cd/32), 2);
c7 = mod(floor(cd/64), 2);
c8 = mod(floor(cd/128), 2);

% combining image again to form equivalent to original grayscale image


cc = (2 * (2 * (2 * (2 * (2 * (2 * (2 * c8 + c7) + c6) + c5) + c4) + c3) + c2) + c1);

% plotting original image in first subplot


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

% plotting binary image having extracted bit from 1st to 8th


% in subplot from 2nd to 9th
subplot(2, 5, 2);
imshow(c1);
title('Bit Plane 1');
subplot(2, 5, 3);
imshow(c2);
title('Bit Plane 2');
subplot(2, 5, 4);
imshow(c3);
title('Bit Plane 3');
subplot(2, 5, 5);
imshow(c4);
title('Bit Plane 4');
subplot(2, 5, 6);
imshow(c5);
title('Bit Plane 5');
subplot(2, 5, 7);
imshow(c6);
title('Bit Plane 6');
subplot(2, 5, 8);
imshow(c7);
title('Bit Plane 7');
subplot(2, 5, 9);
imshow(c8);
title('Bit Plane 8');

% plotting recombined image in 10th subplot


subplot(2, 5, 10);
imshow(uint8(cc));
title('Recombined Image');

BIT SLICING OUTPUT:


EXPERIMENT NO : 4
AIM: DCT / IDCT COMPUTATION:
DCT:
MATLAB CODE:

t = 0:1/1000:1;
x = sin(2*pi*25*t);
y = dct(x);
y2 = find(abs(y) < 0.1);
y(y2) = zeros(size(y2));
z = idct(y);
howmany = length(find(y))
subplot(2,1,1)
plot(t,x)
ax = axis;
title('Original Signal')

subplot(2,1,2)
plot(t,z)
axis(ax)
title('Reconstructed Signal')
DCT OUTPUT:
EXPERIMENT NO: 5
AIM: Program for image enhancement using histogram equalization.
THEORY: Histogram is bar-graph used to profile the occurrence of each gray level in the
image. Mathematically it is represented as h(r ) = n Where r is k grey level and n is number of
k k k
th
k

pixel having that Grey level. Histogram can tell us whether image was scanned properly or not. It
gives us idea about tonal distribution in the image. Histogram equalization can be applied to
improve appearance of the image. Histogram also tells us about objects in the image. Object in
an image have similar gray levels so histogram helps us to select threshold value for object
detection. Histogram can be used for image segmentation.
MATLAB CODE:

clc;
clear all
close all
I = imread('tire.tif');
J = histeq(I);
imshowpair(I,J,'montage')
axis off
figure,imhist(I,64)
figure,imhist(J,64)
%for 3D image
load mristack
enhanced = histeq(mristack);
% Display the first slice of data for the original image and the contrast-enhanced
image.
figure,subplot(1,2,1)
imshow(mristack(:,:,1))
title('Slice of Original Image')
subplot(1,2,2)
imshow(enhanced(:,:,1))
title('Slice of Enhanced Image')
OUTPUT:
EXPERIMENT NO: 6
AIM: Program to filter an image using averaging low pass filter in spatial domain
and median filter.

MATLAB CODE:
img = imread('cameraman.tif');
imgd = im2double(img); % imgd in [0,1]
f = ones(3,3)/9;
img1 = filter2(f, imgd);
subplot(331);imshow(img);
subplot(332);imshow(img1);

imgd = imnoise(imgd,'salt & pepper',0.02);


f = ones(3,3)/9;
img1 = filter2(f, imgd);
subplot(333);imshow(imgd);
subplot(334);imshow(img1);

K = medfilt2(imgd);
subplot(335);imshow(K);

%color image
I = imread('hawk.png');
J = imnoise(I,'salt & pepper',0.02);

% filter each channel separately


r = medfilt2(J(:, :, 1), [3 3]);
g = medfilt2(J(:, :, 2), [3 3]);
b = medfilt2(J(:, :, 3), [3 3]);

% reconstruct the image from r,g,b channels


K1 = cat(3, r, g, b);
subplot(336);imshow(J);
subplot(337);imshow(K1);
subplot(338);imshow(I);

OUTPUT:
EXPERIMENT NO: 8

AIM: Program for detecting edges in an image using Roberts


cross gradient operator and Sobel operator.
MATLAB CODE:
% MATLAB Code | Robert Operator from Scratch
% Read Input Image
input_image = imread('[name of input image file].[file format]');
% Displaying Input Image
input_image = uint8(input_image);
figure, imshow(input_image); title('Input Image');
% Convert the truecolor RGB image to the grayscale image
input_image = rgb2gray(input_image);
% Convert the image to double
input_image = double(input_image);
% Pre-allocate the filtered_image matrix with zeros
filtered_image = zeros(size(input_image));
% Robert Operator Mask
Mx = [1 0; 0 -1];
My = [0 1; -1 0];
% Edge Detection Process
% When i = 1 and j = 1, then filtered_image pixel
% position will be filtered_image(1, 1)
% The mask is of 2x2, so we need to traverse
% to filtered_image(size(input_image, 1) - 1
%, size(input_image, 2) - 1)
for i = 1:size(input_image, 1) - 1
for j = 1:size(input_image, 2) - 1
% Gradient approximations
Gx = sum(sum(Mx.*input_image(i:i+1, j:j+1)));
Gy = sum(sum(My.*input_image(i:i+1, j:j+1)));
% Calculate magnitude of vector
filtered_image(i, j) = sqrt(Gx.^2 + Gy.^2);
end
end
% Displaying Filtered Image
filtered_image = uint8(filtered_image);
figure, imshow(filtered_image); title('Filtered Image');
% Define a threshold value
thresholdValue = 100; % varies between [0 255]
output_image = max(filtered_image, thresholdValue);
output_image(output_image == round(thresholdValue)) = 0;
% Displaying Output Image
output_image = im2bw(output_image);
figure, imshow(output_image); title('Edge Detected Image');

INPUT:
OUTPUT:
FILTERED IMAGE:

EDGE DETECTED IMAGE:


EXPERIMENT NO:9
AIM: To compress data using Huffman Coding.
Theory:
Huffman Coding is one of the lossless data compression techniques. It
assigns variable-length codes to the input characters, based on the
frequencies of their occurence. The most frequent character is given the
smallest length code.

Code:
import
heapq
import os

class HeapNode:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None

def __cmp__(self, other):


if(other == None):
return -1
if(not isinstance(other, HeapNode)):
return -1
return self.freq > other.freq

class HuffmanCoding:
def __init__(self, path):
self.path = path
self.heap = []
self.codes = {}
self.reverse_mapping = {}

# functions for compression:

def make_frequency_dict(self, text):


frequency = {}
for character in text:
if not character in frequency:
frequency[character] = 0
frequency[character] += 1
return frequency

def make_heap(self, frequency):


for key in frequency:
node = HeapNode(key, frequency[key])
heapq.heappush(self.heap, node)

def merge_nodes(self):
while(len(self.heap)>1):
node1 = heapq.heappop(self.heap)
node2 = heapq.heappop(self.heap)

merged = HeapNode(None, node1.freq + node2.freq)


merged.left = node1
merged.right = node2

heapq.heappush(self.heap, merged)

def make_codes_helper(self, root, current_code):


if(root == None):
return
if(root.char != None):
self.codes[root.char] = current_code
self.reverse_mapping[current_code] = root.char
return

self.make_codes_helper(root.left, current_code + "0")


self.make_codes_helper(root.right, current_code + "1")

def make_codes(self):
root = heapq.heappop(self.heap)
current_code = ""
self.make_codes_helper(root, current_code)

def get_encoded_text(self, text):


encoded_text = ""
for character in text:
encoded_text += self.codes[character]
return encoded_text

def pad_encoded_text(self, encoded_text):


extra_padding = 8 - len(encoded_text) % 8
for i in range(extra_padding):
encoded_text += "0"

padded_info = "{0:08b}".format(extra_padding)
encoded_text = padded_info + encoded_text
return encoded_text
def get_byte_array(self, padded_encoded_text):
if(len(padded_encoded_text) % 8 != 0):
print("Encoded text not padded properly")
exit(0)

b = bytearray()
for i in range(0, len(padded_encoded_text), 8):
byte = padded_encoded_text[i:i+8]
b.append(int(byte, 2))
return b

def compress(self):
filename, file_extension = os.path.splitext(self.path)
output_path = filename + ".bin"

with open(self.path, 'r+') as file, open(output_path, 'wb') as output:


text = file.read()
text = text.rstrip()

frequency = self.make_frequency_dict(text)
self.make_heap(frequency)
self.merge_nodes()
self.make_codes()

encoded_text = self.get_encoded_text(text)
padded_encoded_text = self.pad_encoded_text(encoded_text)

b = self.get_byte_array(padded_encoded_text)
output.write(bytes(b))
print("Compressed")
return output_path

""" functions for decompression: """

def remove_padding(self, padded_encoded_text):


padded_info = padded_encoded_text[:8]
extra_padding = int(padded_info, 2)

padded_encoded_text = padded_encoded_text[8:]
encoded_text = padded_encoded_text[:-1*extra_padding]

return encoded_text

def decode_text(self, encoded_text):


current_code = ""
decoded_text = ""

for bit in encoded_text:


current_code += bit
if(current_code in self.reverse_mapping):
character = self.reverse_mapping[current_code]
decoded_text += character
current_code = ""

return decoded_text

def decompress(self, input_path):


filename, file_extension = os.path.splitext(self.path)
output_path = filename + "_decompressed" + ".txt"

with open(input_path, 'rb') as file, open(output_path, 'w') as output:


bit_string = ""

byte = file.read(1)
while(byte != ""):
byte = ord(byte)
bits = bin(byte)[2:].rjust(8, '0')
bit_string += bits
byte = file.read(1)

encoded_text = self.remove_padding(bit_string)

decompressed_text = self.decode_text(encoded_text)

output.write(decompressed_text)

print("Decompressed")
return output_path

Result:
INITIAL SIZE COMPRESSED FILE SIZE

715.3 KB 394.0 KB

Plus, the decompressed file comes out to be exactly the same as the original file,
without any data loss.
EXPERIMENT NO :10
AIM: Program for morphological image operations-erosion,
dilation, opening & closing.
MATLAB CODE:

# Importing the image


I = imread("flowers.jpg"); 
subplot(2, 3, 1),  
imshow(I); 
title("Original image"); 
  
% Dilated Image 
se = strel("line", 7, 7); 
dilate = imdilate(I, se); 
subplot(2, 3, 2),  
imshow(dilate); 
title("Dilated image"); 
  
% Eroded image 
erode = imerode(I, se); 
subplot(2, 3, 3),  
imshow(erode); 
title("Eroded image"); 
  
% Opened image 
open = imopen(I, se); 
subplot(2, 3, 4),  
imshow(open); 
title("Opened image"); 
  
% Closed image 
close = imclose(I, se); 
subplot(2, 3, 5),  
imshow(close); 
title("Closed image"); 
OUTPUT:

You might also like