Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
38 views21 pages

Iva 1

1) The document appears to be a student assignment containing code to perform image processing tasks on an uploaded image. 2) It loads an image, converts it to grayscale, and applies various filters including low pass, high pass, and bit plane slicing. 3) Results of the different filters are plotted and displayed for comparison.

Uploaded by

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

Iva 1

1) The document appears to be a student assignment containing code to perform image processing tasks on an uploaded image. 2) It loads an image, converts it to grayscale, and applies various filters including low pass, high pass, and bit plane slicing. 3) Results of the different filters are plotted and displayed for comparison.

Uploaded by

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

Yash Bhosale

3302
MSc-IT
PRACTICAL 1

import numpy as np # library used for working with arrays


import matplotlib.pylab as plt # library used for ploting, graph
from io import BytesIO
import cv2 # library for Open Source Computer vision library
from PIL import Image # Python Imaging Library for load, display, save
etc
from google.colab.patches import cv2_imshow
from google.colab import files
uploaded = files.upload()
img1=Image.open(BytesIO(uploaded['kite.jpg']))
img2 = cv2.imread("kite.jpg")
#plt.imshow(img2)
gray_img = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
#plt.imshow(gray_img,cmap=plt.cm.gray)

### Negative of the image


[rows,cols] = gray_img.shape;
neg_img = np.zeros((rows,cols));
for r in range(0, rows-1):
for c in range(0, cols-1):
neg_img[r,c] = 255-gray_img[r,c]; #Calculate negative image
#plt.imshow(neg_img, cmap=plt.cm.gray)
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.imshow(img1)
ax1.set_title('Original image')
ax2 = fig.add_subplot(2,2,2)
ax2.imshow(gray_img, cmap=plt.cm.gray)
ax2.set_title('Gray image')
ax3 = fig.add_subplot(2,2,3)
ax3.imshow(neg_img)
ax3.set_title('Negative image')
Yash Bhosale
3302
MSc-IT

# c = 255/(log (1 + m)), where m is the maximum pixel value in the image.


#c = 0.1
c = 255/(np.log(1 + np.max(gray_img)))
log_transformed = c * np.log(1 + gray_img)
log_transformed1 = np.array(log_transformed, dtype = np.uint8)
plt.imshow(log_transformed1, cmap=plt.cm.gray)
Yash Bhosale
3302
MSc-IT
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.imshow(img1)
ax1.set_title('Original image')
ax2 = fig.add_subplot(2,2,2)
ax2.imshow(gray_img, cmap=plt.cm.gray)
ax2.set_title('Gray image')
ax3 = fig.add_subplot(2,2,3)
ax3.imshow(neg_img, cmap=plt.cm.gray)
ax3.set_title('Negative')
ax4 = fig.add_subplot(2,2,4)
ax4.imshow(log_transformed1, cmap=plt.cm.gray)
ax4.set_title('Log image')
Yash Bhosale
3302
MSc-IT

import cv2
import numpy as np
import matplotlib.pyplot as plt
from google.colab import files # Import the files module to upload images

# Function for histogram equalization


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

# Function for contrast stretching


def contrast_stretching(image, r1, r2, s1, s2):
result_image = np.copy(image)
result_image[result_image < r1] = s1
Yash Bhosale
3302
MSc-IT
result_image[(result_image >= r1) & (result_image <= r2)] =
((result_image[(result_image >= r1) & (result_image <= r2)] - r1) * (s2 -
s1)) / (r2 - r1) + s1
result_image[result_image > r2] = s2
return result_image

# Function for gamma correction


def gamma_correction(image, gamma):
corrected_image = np.power(image / 255.0, gamma)
corrected_image = (corrected_image * 255).astype(np.uint8)
return corrected_image

# Function for digital negative


def digital_negative(image):
negative_image = 255 - image
return negative_image

# Upload an image file from your local machine


uploaded = files.upload()

# Check if an image file was uploaded


if len(uploaded) > 0:
# Read the uploaded image
image_filename = list(uploaded.keys())[0]
input_image = cv2.imread(image_filename, cv2.IMREAD_GRAYSCALE)

# Define parameters for contrast stretching


r1 = 5
r2 = 10
s1 = 2
s2 = 12

# Define parameter for gamma correction


gamma = 1.5

# Perform point processing techniques


equalized_image = histogram_equalization(input_image)
contrast_stretched_image = contrast_stretching(input_image, r1, r2,
s1, s2)
Yash Bhosale
3302
MSc-IT
gamma_corrected_image = gamma_correction(input_image, gamma)

# Perform digital negative transformation


negative_image = digital_negative(input_image)

# Create subplots with figsize 10x7


fig, axes = plt.subplots(1, 5, figsize=(10, 7))

# Plot original and processed images


axes[0].imshow(input_image, cmap='gray')
axes[0].set_title('Original Image')

axes[1].imshow(equalized_image, cmap='gray')
axes[1].set_title('Histogram Equalization')

axes[2].imshow(contrast_stretched_image, cmap='gray')
axes[2].set_title('Contrast Stretching')

axes[3].imshow(gamma_corrected_image, cmap='gray')
axes[3].set_title('Gamma Correction')

axes[4].imshow(negative_image, cmap='gray')
axes[4].set_title('Digital Negative')

for ax in axes:
ax.axis('off')

plt.tight_layout()
plt.show()
else:
print("No image uploaded. Please upload an image.")
Yash Bhosale
3302
MSc-IT

from google.colab import files


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

# Prompt the user to upload an image


uploaded = files.upload()

# Check if any files were uploaded


if len(uploaded) == 0:
print("No files uploaded.")
else:
# Get the uploaded image file
file_name = list(uploaded.keys())[0]

# Load the uploaded image using OpenCV


image = cv2.imread(file_name, cv2.IMREAD_GRAYSCALE)

# Number of bits for bit-plane slicing (adjust as needed)


num_bits = 8

# Create subplots for each bit plane


fig, axes = plt.subplots(1, num_bits, figsize=(15, 7))

for i in range(num_bits):
# Create a bitmask to extract the i-th bit plane
bitmask = 2**i
bit_plane = (image & bitmask) * 255 # Scale to 0-255 range

# Display the bit plane


axes[i].imshow(bit_plane, cmap='gray')
Yash Bhosale
3302
MSc-IT
axes[i].set_title(f'Bit {7 - i}') # Reverse order to match binary
representation
axes[i].axis('off')

plt.tight_layout()
plt.show()
Yash Bhosale
3302
MSc-IT
PRACTICAL 2

from io import BytesIO


import numpy as np # library used for working with arrays
import matplotlib.pylab as plt # library used for ploting, graph
import cv2 # library for Open Source Computer vision library
from PIL import Image # Python Imaging Library for load, display, save etc
from google.colab.patches import cv2_imshow
from google.colab import files
uploaded = files.upload()

img1=Image.open(BytesIO(uploaded['thar.jpg']))
plt.imshow(img1)
Yash Bhosale
3302
MSc-IT

img = cv2.imread("thar.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(img,cmap=plt.cm.gray)

# Obtain number of rows and columns of the image


#img = np.array([[88, 38, 41, 42, 42], [98, 32, 38, 121, 33], [12, 255,
46, 1, 10], [123, 25, 246, 0, 19], [12, 5, 46, 10, 11]]) # 01 is not
acceptable
m, n = img.shape
m,n
Yash Bhosale
3302
MSc-IT

#Low Pass Filter


mask1 = np.ones([3, 3], dtype = int) #averaging
mask = mask1 / 9
mask1
#mask

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


img_new
for i in range(1, m-1):
for j in range(1, n-1):
temp = img[i-1, j-1]*mask[-1, -1]+img[i, j-1]*mask[0, -1]+img[i+1,
j-1]*mask[1, -1]+ img[i-1, j]*mask[-1, 0]+img[i, j]*mask[0, 0]+img[i+1,
j]*mask[1, 0]+img[i-1, j+1]*mask[-1, 1]+img[i, j+1]*mask[0, 1]+img[i+1,
j+1]*mask[1, 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
img_new = img_new.astype(np.uint8)
plt.imshow(img_new,cmap=plt.cm.gray)
img_new
Yash Bhosale
3302
MSc-IT

#High Pass Filter


mask2 = np.array([[-1,-1,-1],[-1,8,-1],[-1,-1,-1]]) #High Pass
mask_hpf = mask2 / 9
mask_hpf

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

img_new
mask=mask_hpf
for i in range(1, m-1):
for j in range(1, n-1):
Yash Bhosale
3302
MSc-IT
temp = img[i-1, j-1]*mask[-1, -1]+img[i, j-1]*mask[0, -1]+img[i+1,
j-1]*mask[1, -1]+ img[i-1, j]*mask[-1, 0]+img[i, j]*mask[0, 0]+img[i+1,
j]*mask[1, 0]+img[i-1, j+1]*mask[-1, 1]+img[i, j+1]*mask[0, 1]+img[i+1,
j+1]*mask[1, 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
img_new = img_new.astype(np.uint8)
plt.imshow(img_new,cmap=plt.cm.gray)

img_new

#Apply all filters accordingly


#mask = np.array([[-1,0],[0,1]]) #roberts1
#mask = np.array([[0,-1],[1,0]]) #roberts2
#mask = mask / 9
Yash Bhosale
3302
MSc-IT
#mask = np.array([[-1,-1,-1],[0,0,0],[1,1,1]]) #prewitt_horizontal
#mask = np.array([[-1,0,1],[-1,0,1],[-1,0,1]]) #prewitt_vertical
#mask = np.array([[-1,-2,-1],[0,0,0],[1,2,1]]) #sobel_horizontal
#mask = np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) #sobel_vert
#mask = np.array([[-1,-1,-1],[2,2,2],[-1,-1,-1]]) #horizontal_2nd order
#mask = np.array([[2,-1,-1],[-1,2,-1],[-1,-1,2]]) #45
#mask = np.array([[-1,2,-1],[-1,2,-1],[-1,2,-1]]) #vertical_2nd order
#mask = np.array([[-1,-1,2],[-1,2,-1],[2,-1,-1]]) #-45
Yash Bhosale
3302
MSc-IT

PRACTICAL 3

from io import BytesIO


import numpy as np # library used for working with arrays
import matplotlib.pylab as plt # library used for ploting, graph
import cv2 # library for Open Source Computer vision library
from PIL import Image # Python Imaging Library for load, display, save etc
from google.colab.patches import cv2_imshow
from google.colab import files
uploaded = files.upload()
img=Image.open(BytesIO(uploaded['Parrot.jpg']))
plt.imshow(img)
img = cv2.imread("Parrot.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(img,cmap=plt.cm.gray)

# Obtain number of rows and columnsof the image


#img = np.array([[88, 38, 41, 42, 42], [98, 32, 38, 121, 33], [12, 255,
46, 1, 10], [123, 25, 246, 0, 19], [12, 5, 46, 10, 11]]) # 01 is not
acceptable
m, n = img.shape

m,n

#mask = np.ones([3, 3], dtype = int) #averaging


mask = np.array([[-1,0],[0,1]]) #roberts1
#mask = np.array([[0,-1],[1,0]]) #roberts2
#mask = mask / 9
#mask = np.array([[-1,-1,-1],[0,0,0],[1,1,1]]) #prewitt_horizontal
#mask = np.array([[-1,0,1],[-1,0,1],[-1,0,1]]) #prewitt_vertical
#mask = np.array([[-1,-2,-1],[0,0,0],[1,2,1]]) #sobel_horizontal
#mask = np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) #sobel_vert
#mask = np.array([[-1,-1,-1],[2,2,2],[-1,-1,-1]]) #horizontal_2nd order
#mask = np.array([[2,-1,-1],[-1,2,-1],[-1,-1,2]]) #45
#mask = np.array([[-1,2,-1],[-1,2,-1],[-1,2,-1]]) #vertical_2nd order
Yash Bhosale
3302
MSc-IT
#mask = np.array([[-1,-1,2],[-1,2,-1],[2,-1,-1]]) #-45

mask

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

img_new

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,
j-1]*mask[1, 0]+ img[i, j]*mask[1, 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
img_new = img_new.astype(np.uint8)
plt.imshow(img_new,cmap=plt.cm.gray)

img_new
Yash Bhosale
3302
MSc-IT
Yash Bhosale
3302
MSc-IT

PRACTICAL 4

import cv2
import numpy as np
from google.colab.patches import cv2_imshow

import cv2
import numpy as np
import matplotlib.pyplot as plt # Import matplotlib for subplots

# Define a 10x10 matrix as the input image


input_image = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)

# Define your custom structuring element (kernel)


# In this example, we use a 3x3 rectangular kernel
kernel = np.array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]], dtype=np.uint8)

# Perform Erosion
erosion = cv2.erode(input_image, kernel, iterations=1)

# Perform Dilation
dilation = cv2.dilate(input_image, kernel, iterations=1)

# Perform Opening (Erosion followed by Dilation)


opening = cv2.morphologyEx(input_image, cv2.MORPH_OPEN, kernel)
Yash Bhosale
3302
MSc-IT

# Perform Closing (Dilation followed by Erosion)


closing = cv2.morphologyEx(input_image, cv2.MORPH_CLOSE, kernel)

# Create subplots with figsize 10x7


fig, axes = plt.subplots(1, 5, figsize=(10, 7))

# Plot original and processed images


axes[0].imshow(input_image * 255, cmap='gray') # Scale to 0-255 for
display
axes[0].set_title('Original Image')

axes[1].imshow(erosion * 255, cmap='gray') # Scale to 0-255 for display


axes[1].set_title('Erosion')

axes[2].imshow(dilation * 255, cmap='gray') # Scale to 0-255 for display


axes[2].set_title('Dilation')

axes[3].imshow(opening * 255, cmap='gray') # Scale to 0-255 for display


axes[3].set_title('Opening')

axes[4].imshow(closing * 255, cmap='gray') # Scale to 0-255 for display


axes[4].set_title('Closing')

for ax in axes:
ax.axis('off') # Turn off axes for cleaner display

plt.tight_layout()
plt.show()
Yash Bhosale
3302
MSc-IT
import cv2
import numpy as np
import matplotlib.pyplot as plt
from google.colab import files # Import the files module to upload images

# Function to perform morphology operations and display results


def perform_morphology_operations(input_image, kernel):
erosion = cv2.erode(input_image, kernel, iterations=1)
dilation = cv2.dilate(input_image, kernel, iterations=1)
opening = cv2.morphologyEx(input_image, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(input_image, cv2.MORPH_CLOSE, kernel)

return erosion, dilation, opening, closing

# Upload an image file from your local machine


uploaded = files.upload()

# Check if an image file was uploaded


if len(uploaded) > 0:
# Read the uploaded image
image_filename = list(uploaded.keys())[0]
input_image = cv2.imread(image_filename, cv2.IMREAD_GRAYSCALE)

# Define a custom structuring element (kernel)


kernel = np.array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]], dtype=np.uint8)

# Perform morphology operations


erosion, dilation, opening, closing =
perform_morphology_operations(input_image, kernel)

# Create subplots with figsize 10x7


fig, axes = plt.subplots(1, 5, figsize=(10, 7))

# Plot original and processed images


axes[0].imshow(input_image, cmap='gray')
axes[0].set_title('Original Image')
Yash Bhosale
3302
MSc-IT
axes[1].imshow(erosion, cmap='gray')
axes[1].set_title('Erosion')

axes[2].imshow(dilation, cmap='gray')
axes[2].set_title('Dilation')

axes[3].imshow(opening, cmap='gray')
axes[3].set_title('Opening')

axes[4].imshow(closing, cmap='gray')
axes[4].set_title('Closing')

for ax in axes:
ax.axis('off')

plt.tight_layout()
plt.show()
else:
print("No image uploaded. Please upload an image.")

You might also like