[go: up one dir, main page]

0% found this document useful (0 votes)
10 views23 pages

DIP FILE(1)

Uploaded by

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

DIP FILE(1)

Uploaded by

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

GURU TEGH BAHADUR

INSTITUTE OF TECHNOLOGY

Digital Image Processing


Practical File
Submitted by:
Name: Japjyot Singh
Branch: AI-DS
Roll no. 04313211921

Japjyot singh 04313211921 AI-DS


INDEX

Date of Date of Teacher’s


S.No. Topic
Experiment Submission Signature

Create a program to demonstrate


1. Geometric transformations- Image
rotation, scaling, and translation.

Display of FFT (1-D & 2-D) of an


image and apply Two-
dimensional Fourier transform to
2.
represent the content of an image
using the discrete Fourier
transform (DFT) and masking
with DFT.
Write a Program of Contrast
stretching of a low contrast image,
3. Histogram, and Histogram
Equalization and Display of bit
planes of an Image.

Computation of Mean, Standard


4. Deviation, Correlation coefficient of
the given Image.

Implementation of image
5. Smoothening Filters (Mean and
Median filtering of an image)

Implementation of image
sharpening filters and Edge
6.
Detection using Gradient
Filters.

Implementation of image Intensity


slicing technique for image
7.
enhancement.

Study and implement Canny edge


detection Algorithm to images and
8.
compare it with the existing edge
detection algorithms.

Japjyot Singh 04313211921 AI-DS


EXPERIMENT 1

Aim: Create a program to demonstrate Geometric transformations- Image


rotation, scaling, and translation.

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

# Read the image


I = cv2.imread('EXP1.jpg')
# Display the original image
plt.subplot(2, 2, 1)
plt.imshow(cv2.cvtColor(I, cv2.COLOR_BGR2RGB))
plt.title('Original Image')

# Input scaling factor


s = float(input('Enter Scaling Factor: '))

# Resize the image


j = cv2.resize(I, None, fx=s, fy=s)
# Display the scaled image
plt.subplot(2, 2, 2)
plt.imshow(cv2.cvtColor(j, cv2.COLOR_BGR2RGB))
plt.title('Scaled Image')
# Input rotation angle
angle = float(input('Enter Rotation Angle in degrees: '))

# Rotate the image


rows, cols, _ = j.shape
M = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)
K = cv2.warpAffine(j, M, (cols, rows))
# Display the rotated image
plt.subplot(2, 2, 3)
plt.imshow(cv2.cvtColor(K, cv2.COLOR_BGR2RGB))
plt.title(f'Rotated Image {angle} deg')

Japjyot Singh 04313211921 AI-DS


# Input translation values
tx = float(input('Enter translation in x direction (pixels): '))
ty = float(input('Enter translation in y direction (pixels): '))

# Define translation matrix


M = np.float32([[1, 0, tx], [0, 1, ty]])
# Apply translation
translated_image = cv2.warpAffine(K, M, (cols, rows))
# Display the translated image
plt.subplot(2, 2, 4)
plt.imshow(cv2.cvtColor(translated_image, cv2.COLOR_BGR2RGB))
plt.title('Translated Image')

Output:

Japjyot Singh 04313211921 AI-DS


EXPERIMENT 2

Aim: Display of FFT (1-D & 2-D) of an image and apply Two-dimensional
Fourier transform to represent the content of an image using the discrete Fourier
transform (DFT) and masking with DFT.

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

Japjyot Singh 04313211921 AI-DS


Read the image
image = cv2.imread('EXP 2.jpg', cv2.IMREAD_GRAYSCALE)
# Display the original image
plt.subplot(2, 3, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')

# Compute 1-D FFT


fft_1d = np.fft.fft(image[0])

# Plot 1-D FFT


plt.subplot(2, 3, 2)
plt.plot(np.abs(fft_1d))
plt.title('1-D FFT')

# Compute 2-D FFT


fft_2d =
np.fft.fft2(image)

# Shift the zero frequency component to the center


fft_2d_shifted = np.fft.fftshift(fft_2d)

# Plot magnitude of 2-D FFT


plt.subplot(2, 3, 3)
plt.imshow(np.log(1 + np.abs(fft_2d_shifted)), cmap='gray')
plt.title('Magnitude of 2-D FFT')

# Apply mask to the 2-D FFT


mask = np.zeros_like(fft_2d_shifted)
mask[100:400, 100:400] = 1 # Defining a square mask
fft_2d_shifted_masked = fft_2d_shifted * mask

# Plot masked 2-D FFT


plt.subplot(2, 3, 4)
plt.imshow(np.log(1 + np.abs(fft_2d_shifted_masked)), cmap='gray')
plt.title('Masked 2-D FFT')

# Inverse FFT to obtain the masked image


masked_image = np.fft.ifft2(np.fft.ifftshift(fft_2d_shifted_masked)).real

# Display the masked image


Japjyot Singh 04313211921 AI-DS
plt.subplot(2, 3, 5)
plt.imshow(masked_image, cmap='gray')
plt.title('Masked Image')

# Show plots
plt.tight_layout()
plt.show()

Output:

EXPERIMENT 3

Aim: Write a Program of Contrast stretching of a low contrast image,


Histogram, and Histogram Equalization and Display of bit planes of an Image.

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

# Function for contrast stretching

Japjyot Singh 04313211921 AI-DS


def contrast_stretching(image, min_value, max_value):
normalized_image = cv2.normalize(image, None, min_value, max_value,
cv2.NORM_MINMAX)
return normalized_image

# Function for histogram equalization


def histogram_equalization(image):
equalized_image = cv2.equalizeHist(image)
return equalized_image

# Function to display bit planes of an image


def display_bit_planes(image):
bit_planes = [cv2.bitwise_and(image, 1 << i) for i in range(8)]
return bit_planes

# Read the image


image = cv2.imread('EXP 2.jpg', cv2.IMREAD_GRAYSCALE)

# Check if the image is loaded successfully


if image is None:
print("Error: Failed to read the image.")
else:
print("Image loaded successfully.")

# Display the original image


plt.subplot(3, 3, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image (OI)')

# Contrast Stretching
min_value = 0
max_value = 255
stretched_image = contrast_stretching(image, min_value, max_value)
plt.subplot(3, 3, 2)
plt.imshow(stretched_image, cmap='gray')
plt.title('Contrast Stretched Image (SI)')

# Histogram Equalization
equalized_image = histogram_equalization(image)
plt.subplot(3, 3, 3)

Japjyot Singh 04313211921 AI-DS


plt.imshow(equalized_image, cmap='gray')
plt.title('Equalized Image (EI)')

# Display Histogram
plt.subplot(3, 3, 4)
plt.hist(image.flatten(), bins=256, range=[0, 256], color='r')
plt.title('Histogram of OI')

plt.subplot(3, 3, 5)
plt.hist(stretched_image.flatten(), bins=256, range=[0, 256], color='g')
plt.title('Histogram of SI')

plt.subplot(3, 3, 6)
plt.hist(equalized_image.flatten(), bins=256, range=[0, 256], color='b')
plt.title('Histogram of EI')

plt.tight_layout()
plt.show()

# Display bit planes


bit_planes = display_bit_planes(image)
for i in range(8):
plt.subplot(3, 3, i+1)
plt.imshow(bit_planes[i], cmap='gray')
plt.title(f'BIT PLANE {i}')
plt.tight_layout()

Japjyot Singh 04313211921 AI-DS


Output:

Japjyot Singh 04313211921 AI-DS


EXPERIMENT 4

Aim: Computation of Mean, Standard Deviation, Correlation coefficient of the


given Image.
Code:
import cv2
import numpy as np

# Read the image


image = cv2.imread('EXP3.jpg', cv2.IMREAD_GRAYSCALE)

# Compute the mean and standard deviation


mean_value = np.mean(image)
std_dev = np.std(image)

# Display the mean and standard deviation


print("Mean:", mean_value)
print("Standard Deviation:", std_dev)

# Generate two random checkerboard patterns


checkerboard1 = np.random.randint(0, 256, size=image.shape, dtype=np.uint8)
checkerboard2 = np.random.randint(0, 256, size=image.shape, dtype=np.uint8)

# Compute the correlation coefficient between the two checkerboard patterns


correlation = np.corrcoef(checkerboard1.flatten(), checkerboard2.flatten())[0, 1]

# Display the correlation coefficient


print("Correlation Coefficient:", correlation)

# Display the grayscale image


plt.subplot(2, 3, 2)
plt.imshow(image, cmap='gray')
plt.title('Grayscale Image')

Japjyot Singh 04313211921 AI-DS


Output:

Japjyot Singh 04313211921 AI-DS


EXPERIMENT 5

Aim: Implementation of image Smoothening Filters (Mean and Median filtering


of an image)

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

# Read the image


img = cv2.imread('IMG8.png', 0)

# Obtain number of rows and columns of the image


m, n = img.shape

# Develop Averaging filter(3, 3) mask


mask = np.ones([3, 3], dtype=int) / 1000

# Convolve the 3X3 mask over the image


img_new = np.zeros([m, n])

for i in range(1, m-1):


for j in range(1, n-1):
temp = img[i-1, j-1] * mask[0, 0] + img[i-1, j] * mask[0, 1] + img[i-1, j + 1]
* mask[0, 2] + \
img[i, j-1] * mask[1, 0] + img[i, j] * mask[1, 1] + img[i, j + 1] *
mask[1, 2] + \
img[i + 1, j-1] * mask[2, 0] + img[i + 1, j] * mask[2, 1] + img[i + 1, j
+ 1] * mask[2, 2]

img_new[i, j] = temp

# Convert the result to uint8 data type


img_new =
img_new.astype(np.uint8)

# Save the blurred image


cv2.imwrite('blurred.tif', img_new)

Japjyot Singh 04313211921 AI-DS


# Display the original and blurred images
plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Original Image')

plt.subplot(1, 2, 2)
plt.imshow(img_new, cmap='gray')
plt.title('Blurred Image')

plt.show()
import cv2
import numpy as np
import matplotlib.pyplot as plt

# Read the noisy image


img_noisy1 = cv2.imread('IMG8.png', 0)

# Obtain the number of rows and columns of the image


m, n = img_noisy1.shape

# Traverse the image. For every 3X3


area, # find the median of the pixels and
# replace the center pixel by the median
img_new1 = np.zeros([m, n])

for i in range(1, m-1):


for j in range(1, n-1):
temp = [img_noisy1[i-1, j-1],
img_noisy1[i-1, j],
img_noisy1[i-1, j + 1],
img_noisy1[i, j-1],
img_noisy1[i, j],
img_noisy1[i, j + 1],
img_noisy1[i + 1, j-1],
img_noisy1[i + 1, j],
img_noisy1[i + 1, j + 1]]

Japjyot Singh 04313211921 AI-DS


temp = sorted(temp)
img_new1[i, j]= temp[4]

img_new1 = img_new1.astype(np.uint8)

# Save the filtered image


cv2.imwrite('new_median_filtered.png', img_new1)

# Display the original and filtered images


plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)
plt.imshow(img_noisy1, cmap='gray')
plt.title('Noisy Image')

plt.subplot(1, 2, 2)
plt.imshow(img_new1, cmap='gray')
plt.title('Median Filtered Image')

plt.show()

Output:

Japjyot Singh 04313211921 AI-DS


Japjyot Singh 04313211921 AI-DS
EXPERIMENT 6

Aim: Implementation of image sharpening filters and Edge Detection using


Gradient Filters.

Code:
import cv2
import numpy as np
from matplotlib import pyplot as plt

# Read the image


img = cv2.imread('EXP4.jpg')

# Convert to grayscale
gray = cv2.cvtColor(img,

cv2.COLOR_BGR2GRAY) plt.figure(figsize=(12,

10))

# Display original image


plt.subplot(4, 2, 1)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title('Original Image')

# Display grayscale image


plt.subplot(4, 2, 2)
plt.imshow(gray, cmap='gray')
plt.title('Gray Image')

# Laplacian filter
laplacian = cv2.Laplacian(gray, cv2.CV_64F)
laplacian = np.uint8(np.absolute(laplacian)) # Convert back to uint8 for
visualization
plt.subplot(4, 2, 3)
plt.imshow(laplacian, cmap='gray')
plt.title('Laplacian')

# Sobel edge detection


Japjyot Singh 04313211921 AI-DS
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0,
ksize=5) sobely = cv2.Sobel(gray, cv2.CV_64F, 0,
1, ksize=5) sobel = np.sqrt(sobelx**2 + sobely**2)
plt.subplot(4, 2, 4)
plt.imshow(sobel, cmap='gray')
plt.title('Sobel')

# Prewitt edge detection


prewittx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
prewitty = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
prewitt = np.sqrt(prewittx**2 + prewitty**2)
plt.subplot(4, 2, 5)
plt.imshow(prewitt, cmap='gray')
plt.title('Prewitt')

# Roberts edge detection


robertsx = cv2.filter2D(gray, -1, np.array([[1, 0], [0, -1]]))
robertsy = cv2.filter2D(gray, -1, np.array([[0, 1], [-1,
0]])) roberts = np.sqrt(robertsx**2 + robertsy**2)
plt.subplot(4, 2, 6)
plt.imshow(roberts, cmap='gray')
plt.title('Roberts')

# Sobel edge detection (horizontal and vertical)


sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5)
sobel_horizontal = cv2.convertScaleAbs(sobelx)
sobel_vertical = cv2.convertScaleAbs(sobely)
plt.subplot(4, 2, 7)
plt.imshow(sobel_horizontal, cmap='gray')
plt.title('Sobel Horizontal')
plt.subplot(4, 2, 8)
plt.imshow(sobel_vertical, cmap='gray')
plt.title('Sobel Vertical')

plt.tight_layout()
plt.show()

Japjyot Singh 04313211921 AI-DS


Output:

Japjyot Singh 04313211921 AI-DS


EXPERIMENT 7

Aim: Implementation of image Intensity slicing technique for image


enhancement.

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

# Read the image


img = cv2.imread('IMG6.jpg', cv2.IMREAD_GRAYSCALE)

# Check if the image is loaded successfully


if img is None:
print("Error: Unable to read the image.")
else:
# Define intensity slicing parameters
low_threshold = 100
high_threshold = 200

# Apply intensity slicing


sliced_img = np.copy(img)
sliced_img[(img >= low_threshold) & (img <= high_threshold)] = 255 #
Enhance pixels within the specified range
sliced_img[(img < low_threshold) | (img > high_threshold)] = 0 # Keep
other pixels unchanged

# Display original and sliced images


plt.figure(figsize=(12, 6))

plt.subplot(1, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Original Image')

plt.subplot(1, 2, 2)
plt.imshow(sliced_img, cmap='gray')

Japjyot Singh 04313211921 AI-DS


plt.title('Intensity Sliced Image')

plt.show()

Output:

Japjyot Singh 04313211921 AI-DS


EXPERIMENT 8

Aim: Study and implement Canny edge detection Algorithm to images and
compare it with the existing edge detection algorithms.

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

# Read the image


img = cv2.imread('IMG1.jpg', cv2.IMREAD_GRAYSCALE)

# Apply Canny edge detection


canny_edges = cv2.Canny(img, 100, 200)

# Apply Sobel edge detection


sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0,
ksize=3) sobely = cv2.Sobel(img, cv2.CV_64F, 0,
1, ksize=3) sobel_edges = np.sqrt(sobelx**2 +
sobely**2)

# Apply Prewitt edge detection


prewittx = cv2.Sobel(img, cv2.CV_64F, 1, 0,
ksize=3) prewitty = cv2.Sobel(img, cv2.CV_64F, 0,
1, ksize=3) prewitt_edges = np.sqrt(prewittx**2 +
prewitty**2)

# Display original and edge-detected images


plt.figure(figsize=(12, 6))

# First row with two subplots


plt.subplot(2, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Original Image')

plt.subplot(2, 2, 2)
plt.imshow(canny_edges, cmap='gray')
plt.title('Canny Edge Detection')

Japjyot Singh 04313211921 AI-DS


# Second row with two subplots
plt.subplot(2, 2, 3)
plt.imshow(sobel_edges, cmap='gray')
plt.title('Sobel Edge Detection')

plt.subplot(2, 2, 4)
plt.imshow(prewitt_edges, cmap='gray')
plt.title('Prewitt Edge Detection')

plt.tight_layout()
plt.show()

Output:

Japjyot Singh 04313211921 AI-DS

You might also like