0% found this document useful (0 votes)
31 views

DIP Lab Assignments

The document contains 9 programs demonstrating different digital image processing techniques like quantization, downsampling, bit plane slicing, histogram equalization, filtering, Fourier transforms, noise addition and removal through operations like erosion, dilation and boundary detection on various test images.

Uploaded by

rr3870044
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

DIP Lab Assignments

The document contains 9 programs demonstrating different digital image processing techniques like quantization, downsampling, bit plane slicing, histogram equalization, filtering, Fourier transforms, noise addition and removal through operations like erosion, dilation and boundary detection on various test images.

Uploaded by

rr3870044
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Digital Image Processing

(Program From 1 to 10)


Name: Gulshan Kumar
Course: MCA 3rd Sem
Roll No. : 22PGMCA15

1. Write a program to demonstrate quantization.

import matplotlib.pyplot as plt


import numpy as np

im = plt.imread('cameraman.tif')
plt.imshow(im)
plt.title('Original Image')
plt.show()

im_d = im.astype(float)
c0 = np.mod(im_d, 2)
plt.imshow(c0)
plt.title('Zero bit Image')
plt.show()

c1 = np.mod(np.floor(im_d/2), 2)
plt.imshow(c1)
plt.title('First bit Image')
plt.show()

c2 = np.mod(np.floor(im_d/4), 2)
plt.imshow(c2)
plt.title('Second bit Image')
plt.show()

c3 = np.mod(np.floor(im_d/8), 2)
plt.imshow(c3)
plt.title('Third bit Image')
plt.show()

c4 = np.mod(np.floor(im_d/16), 2)
plt.imshow(c4)
plt.title('Fourth bit Image')
plt.show()

c5 = np.mod(np.floor(im_d/32), 2)
plt.imshow(c5)
plt.title('Fifth bit Image')
plt.show()

c6 = np.mod(np.floor(im_d/64), 2)
plt.imshow(c6)
plt.title('Sixth bit Image')
plt.show()

c7 = np.mod(np.floor(im_d/128), 2)
plt.imshow(c7)
plt.title('Seventh bit Image')
plt.show()

cc = 2*(2*(2*(2*(2*(2*(2*c7+c6)+c5)+c4)+c3)+c2)+c1)+c0
plt.imshow(cc.astype(np.uint8))
plt.title('Reconstructed Original Image')
plt.show()
2. Write a program to demonstrate down sampling.

import cv2
import matplotlib.pyplot as plt

im = cv2.imread('pout.tif', 0)
plt.imshow(im, cmap='gray')
plt.title('Original image')
plt.show()

plt.hist(im.ravel(), bins=256, range=[0,256])


plt.axis('tight')
plt.title('Image Histogram')
plt.show()

im_h = cv2.equalizeHist(im)
plt.imshow(im_h, cmap='gray')
plt.title('Histogram equalized image')
plt.show()

plt.hist(im_h.ravel(), bins=256, range=[0,256])


plt.axis('tight')
plt.title('Histogram of equalized image')
plt.show()
3. Write a program to perform bit plain slicing.

import cv2
import numpy as np
import matplotlib.pyplot as plt

I = cv2.imread('cameraman.tif', cv2.IMREAD_GRAYSCALE)
plt.subplot(2,2,1)
plt.imshow(I, cmap='gray')
plt.title('Original Image')

H = np.zeros((20, 20))
H[10, :] = 1
H = H / np.sum(H)
MotionBlur = cv2.filter2D(I, -1, H, borderType=cv2.BORDER_REPLICATE)
plt.subplot(2,2,2)
plt.imshow(MotionBlur, cmap='gray')
plt.title('Motion Blurred Image')

H = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))


blurred = cv2.filter2D(I, -1, H, borderType=cv2.BORDER_REPLICATE)
plt.subplot(2,2,3)
plt.imshow(blurred, cmap='gray')
plt.title('Blurred Image')

H = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])


sharpened = cv2.filter2D(I, -1, H, borderType=cv2.BORDER_REPLICATE)
plt.subplot(2,2,4)
plt.imshow(sharpened, cmap='gray')
plt.title('Sharpened Image')

plt.show()
4. Write a program to demonstrate histogram equalization.

import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fftshift, fft2
from PIL import Image

a = np.zeros((256, 256))
a[78:178, 78:178] = 1
plt.imshow(a), plt.title('Image with a square')
plt.show()

af = fftshift(fft2(a))
plt.imshow(np.log(1 + np.abs(af))), plt.title('Fourier transform of square image')
plt.show()

x, y = np.meshgrid(np.arange(1, 257), np.arange(1, 257))


b = (x + y < 329) & (x + y > 182) & (x - y > -67) & (x - y < 73)
plt.imshow(b), plt.title('Rotated square image')
plt.show()

bf = fftshift(fft2(b))
plt.imshow(np.log(1 + np.abs(bf))), plt.title('Fourier transform of rotated square
image')
plt.show()

x, y = np.meshgrid(np.arange(-128, 218), np.arange(-128, 128))


c = np.array(Image.open('cameraman.tif'))
plt.imshow(c), plt.title('Cameraman image')
plt.show()

cf = fftshift(fft2(c))
plt.imshow(np.log(1 + np.abs(cf))), plt.title('Fourier transform of Cameraman
image')
plt.show()

p, q = np.meshgrid(np.arange(-128, 218), np.arange(-128, 128))


r = np.sqrt(p**2 + q**2)
s = (r < 15)
cf = fftshift(fft2(s))
plt.imshow(s), plt.title('Circle')
plt.show()
plt.imshow(np.log(1 + np.abs(cf))), plt.title('Fourier transform of Circle')
plt.show()
5. Write a program to smoothing and sharpening using spatial filters.

import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fftshift, fft2, ifft2

cm = plt.imread('cameraman.tif')
plt.imshow(cm)
plt.title('Input image')
plt.show()

cf = fftshift(fft2(cm))
plt.imshow(np.log(1 + np.abs(cf)))
plt.title('Fourier transform of input image')
plt.show()

x, y = np.meshgrid(np.arange(-128, 128), np.arange(-128, 128))


z = np.sqrt(x**2 + y**2)
c = (z < 15) # Ideal lowpass filter
cfl = cf * c
plt.imshow(np.log(1 + np.abs(cfl)))
plt.title('Ideal lowpass filter')
plt.show()

cfli = ifft2(cfl)
plt.imshow(np.abs(cfli))
plt.title('Image smoothing using ideal lowpass filter')
plt.show()

c = (z > 15) # Ideal highpass filter


cfh = cf * c
plt.imshow(np.log(1 + np.abs(cfh)))
plt.title('Ideal highpass filter')
plt.show()

cfhi = ifft2(cfh)
plt.imshow(np.abs(cfhi))
plt.title('Image sharpening using ideal highpass filter')
plt.show()
6. Write a program to generate Fourier transform of an image.

# Assignment 6: Noise generation


import cv2
import numpy as np

# Load the image


tw = cv2.imread('cameraman.tif')
cv2.imshow('Input image', tw)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Add salt and pepper noise


t_sp = cv2.imread('cameraman.tif')
noise = np.random.randint(0, 2, size=t_sp.shape[:2])
t_sp[noise == 0] = 0
t_sp[noise == 1] = 255
cv2.imshow('Image with salt & pepper noise', t_sp)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Add Gaussian noise


t_ga = cv2.imread('cameraman.tif')
mean = 0
stddev = 50
noise = np.random.normal(mean, stddev, size=t_ga.shape).astype(np.uint8)
t_ga = cv2.add(t_ga, noise)
cv2.imshow('Image with Gaussian noise', t_ga)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Add speckle noise


t_spk = cv2.imread('cameraman.tif')
noise = np.random.randn(*t_spk.shape).astype(np.uint8)
t_spk = t_spk + t_spk * noise
cv2.imshow('Image with speckle noise', t_spk)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Add periodic noise


t_pn = cv2.imread('cameraman.tif')
s = t_pn.shape
x, y = np.meshgrid(np.arange(s[1]), np.arange(s[0]))
p = np.sin(x / 3 + y / 5) + 1
t_pn = (t_pn.astype(np.float32) + p / 2) / 2
cv2.imshow('Image with periodic noise', t_pn)
cv2.waitKey(0)
cv2.destroyAllWindows()

7. Write a program to perform image smoothing and sharpening


using Ideal filters.

# Assignment 7: Noise removal


import cv2
import numpy as np

# Read the input image


t = cv2.imread('cameraman.tif', 0)
cv2.imshow('Input image', t)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Add salt and pepper noise to the image


t_sp = cv2.imread('cameraman.tif', 0)
t_sp = cv2.cvtColor(t_sp, cv2.COLOR_BGR2GRAY)
noise = np.random.randint(0, 2, size=t_sp.shape)
t_sp[noise == 0] = 0
t_sp[noise == 1] = 255
cv2.imshow('Image with salt & pepper noise', t_sp)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Apply 3x3 averaging filter


a3 = np.ones((3, 3), dtype=np.float32) / 9
t_sp_a3 = cv2.filter2D(t_sp, -1, a3)
cv2.imshow('3x3 averaging', t_sp_a3)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Apply 7x7 averaging filter


a7 = np.ones((7, 7), dtype=np.float32) / 49
t_sp_a7 = cv2.filter2D(t_sp, -1, a7)
cv2.imshow('7x7 averaging', t_sp_a7)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Apply median filtering


t_sp_m3 = cv2.medianBlur(t_sp, 3)
cv2.imshow('Median filtering', t_sp_m3)
cv2.waitKey(0)
cv2.destroyAllWindows()
8. Write a program to add different noise to an image.

# Assignment 8: Dilation and erosion


import cv2
import numpy as np
import matplotlib.pyplot as plt

# Read the image


t = cv2.imread('text.jpg', 0)

# Convert the image to binary


t = cv2.threshold(t, 127, 255, cv2.THRESH_BINARY)[1]

# Create a square structuring element


sq = np.ones((2, 2), np.uint8)

# Perform dilation
td = cv2.dilate(t, sq, iterations=1)

# Display the original image


plt.subplot(1, 4, 1)
plt.imshow(t, cmap='gray')
plt.title('Original image')

# Display the dilated image


plt.subplot(1, 4, 2)
plt.imshow(td, cmap='gray')
plt.title('Dilated image')

# Perform erosion
ce = cv2.erode(t, sq, iterations=1)

# Display the eroded image


plt.subplot(1, 4, 3)
plt.imshow(ce, cmap='gray')
plt.title('Eroded image')

# Create a larger square structuring element


sq = np.ones((3, 3), np.uint8)

# Perform erosion with the larger structuring element


ce = cv2.erode(t, sq, iterations=1)

# Display the eroded image with the larger structuring element


plt.subplot(1, 4, 4)
plt.imshow(ce, cmap='gray')
plt.title('Eroded image')

# Show all the plots


plt.show()
9. Write a program to remove noise from an image.

# Assignment 9: Boundary detection


import cv2
import numpy as np
import matplotlib.pyplot as plt

im = cv2.imread('rice.png', 0)
r = cv2.threshold(im, 127, 255, cv2.THRESH_BINARY)[1]
sq = np.ones((3,3), np.uint8)
re = cv2.erode(r, sq)
r_int = cv2.bitwise_and(r, cv2.bitwise_not(re))

plt.subplot(2,2,1),plt.imshow(im, cmap='gray'), plt.title('Input image')


plt.subplot(2,2,2),plt.imshow(r_int, cmap='gray'), plt.title('Internal boundary')
rd = cv2.dilate(r, sq)
r_ext = cv2.bitwise_and(rd, cv2.bitwise_not(r))
r_grad = cv2.bitwise_and(rd, cv2.bitwise_not(re))

plt.subplot(2,2,3),plt.imshow(r_ext, cmap='gray'), plt.title('External boundary')


plt.subplot(2,2,4),plt.imshow(r_grad, cmap='gray'), plt.title('Morphological
gradient')

plt.show()
10. Write a program to demonstrate dilation and erosion.

# Assignment 10: Morphological Opening and closing


import cv2
import numpy as np

# Read the image


c = cv2.imread('circles.jpg', 0)

# Convert the image to binary


c = cv2.threshold(c, 127, 255, cv2.THRESH_BINARY)[1]

# Generate random noise


x = np.random.rand(*c.shape)

# Apply noise to the image


d1 = np.where(x <= 0.05)
d2 = np.where(x >= 0.95)
c[d1] = 0
c[d2] = 1

# Display the image with noise


cv2.imshow('Circle image with noise', c)
cv2.waitKey(0)

# Define the structuring elements


sq = np.ones((3, 3), np.uint8)
cr = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], np.uint8)

# Perform closing and opening operations with square structuring element


cf1 = cv2.morphologyEx(c, cv2.MORPH_CLOSE, sq)
cf1 = cv2.morphologyEx(cf1, cv2.MORPH_OPEN, sq)

# Display the result


cv2.imshow('Closing & Opening with Square SE', cf1)
cv2.waitKey(0)

# Perform closing and opening operations with cross structuring element


cf2 = cv2.morphologyEx(c, cv2.MORPH_CLOSE, cr)
cf2 = cv2.morphologyEx(cf2, cv2.MORPH_OPEN, cr)

# Display the result


cv2.imshow('Closing & Opening with cross SE', cf2)
cv2.waitKey(0)

# Close all windows


cv2.destroyAllWindows()

You might also like