0% found this document useful (0 votes)
30 views14 pages

Shubham Image File

The document provides code snippets to perform various image processing operations using OpenCV in Python. These include reading, displaying and writing images, resizing, color conversion, padding, arithmetic, logical, geometric transformations, intensity transformations, spatial filtering, Laplacian filtering, histogram equalization and morphological operations like erosion and dilation.
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)
30 views14 pages

Shubham Image File

The document provides code snippets to perform various image processing operations using OpenCV in Python. These include reading, displaying and writing images, resizing, color conversion, padding, arithmetic, logical, geometric transformations, intensity transformations, spatial filtering, Laplacian filtering, histogram equalization and morphological operations like erosion and dilation.
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/ 14

Q1 - Write a computer program capable of performing the given basic operations in OpenCV.

A - Read an image Display the image B - Find the shape of the image C - Resize it to a desired size

D - Write the resized image E - Convert to grayscale image F - Pad the image

#CODE

from google.colab import drive

drive.mount('/content/drive')

import cv2

import matplotlib.pyplot as plt

import os

import numpy as np

img = cv2.imread('/content/Lana.png')

plt.imshow(img)

plt.show()

rimg = cv2.resize(img, (256, 256))

path = '/content/Lana.png'

plt.imshow(rimg)

plt.show()

path = '/content/Lana.png'

cv2.imwrite(os.path.join(path, 'LANAmam.jpg'), rimg)

cv2.waitKey(0)

print(rimg.shape)
cimg = cv2.cvtColor(rimg, cv2.COLOR_BGR2RGB)

plt.imshow(cimg)

plt.show()

x = cv2.copyMakeBorder(cimg, 50,50,50,50,
cv2.BORDER_CONSTANT, value= (0,0,0))

plt.imshow(x)

y = cv2.copyMakeBorder(cimg, 50,50,50,50, cv2.BORDER_REPLICATE, value= (200,200,200))

plt.imshow(y)
Q2 - Write a computer program capable of performing the given arithmetic operations between two
images.

A – Addition B – Subtraction C- Multiplication D - Division

#CODE

#Addition

print(img1.shape)

print(img2.shape)

img2 = cv2.resize(img2, (512, 512))

print(img1.shape)

print(img2.shape)

dst = cv2.addWeighted(img2,0.7,img1,0.3,0)

dst = cv2.add(img2,img1)

plt.imshow(dst)

#Multiplication

dstmultiply=cv2.multiply(img1,img2)

plt.imshow(dstmultiply)

#Division

dstdivide=cv2.divide(img1,img2)

plt.imshow(dstdivide)

#Subtraction

dstsub=cv2.subtract(img1,img2)

plt.imshow(dstdivide)
Q3 - Write a computer program capable of performing the given Bitwise logical operations between two
images.

 Bitwise AND
 Bitwise OR
 Bitwise XOR
 Bitwise NOT

#CODE

X = cv2.bitwise_and(img1,img2)

plt.imshow(x)

y = cv2.bitwise_or(img1,img2)

plt.imshow(y)

z = cv2.bitwise_not(img1)

plt.imshow(z)

w = cv2.bitwise_xor(img1,img2)

plt.imshow(w)
Q4 - Write a computer program capable of performing the given geometric transformations on an image

 Translation
 Rotation
 Scaling
 Vertical shear
 Horizontal shear
 Reflection

#CODE

#Affine Transformations - SCALING the image or resizing

rows,cols,dim=img.shape

#M=np.float32([[2,0,0],[0,2,0]])

M=np.float32([[2,0,0],[0,2,0],[0,0,1]])

#simg=cv2.warpAffine(img,M,(cols*2,rows*4))

simg = cv2.warpPerspective(img,M,(cols*2,rows*2))

plt.imshow(simg)

print(simg.shape)

#ROTATION

angle = np.radians(10)

#transformation matrix for Rotation

#M = np.float32([[np.cos(angle), -(np.sin(angle)), 0],

# [np.sin(angle), np.cos(angle), 0]

# ])

#M = np.float32([[np.cos(angle), -(np.sin(angle)), 0],

# [np.sin(angle), np.cos(angle), 0],

# [0, 0, 1]])

# apply a perspective transformation to the image


#rotated_img = cv2.warpAffine(img, M, (int(cols),int(rows)))

#rotated_img = cv2.warpPerspective(img, M, (int(cols),int(rows)))

plt.imshow(rotated_img)

#TRANSLATION

#M_left=np.float32([[1,0,-50],[0,1,0],[0,0,1]])

M_left=np.float32([[1,0,-50],[0,1,0]])

#M_right=np.float32([[1,0,50],[0,1,0]])

#M_bottom=np.float32([[1,0,0],[0,1,50]])

#M_top=np.float32([[1,0,0],[0,1,-50]])

#trans_dst=cv2.warpPerspective(img, M_left,(cols,rows))

trans_dst=cv2.warpAffine(img, M_left,(cols,rows))

plt.imshow(trans_dst)

#SHEAR

#along x axis

#M=np.float32([[1,0.5,0],[0,1,0]])

#M=np.float32([[1,0.5,0],[0,1,0],[0,0,1]])

#sheared_img = cv2.warpAffine(img,M,
(int(cols*1.5),int(rows*1.5)))

#along y axis

#M=np.float32([[1,0,0],[0.5,1,0]])

M=np.float32([[1,0,0],[0.5,1,0],[0,0,1]])

#sheared_img = cv2.warpAffine(img,M,(int(cols*1.5),int(rows*1.5)))

sheared_img = cv2.warpPerspective(img,M,(int(cols*1.5),int(rows*1.5)))

plt.imshow(sheared_img)
#REFLECTION

# transformation matrix for x-axis reflection

#M = np.float32([[1, 0, 0 ],

# [0, -1, rows],

# [0, 0, 1 ]])

# transformation matrix for y-axis reflection

M = np.float32([[-1, 0, cols],

[ 0, 1, 0],

[ 0, 0, 1]])

reflected_img = cv2.warpPerspective(img,M,(int(cols),int(rows)))

plt.imshow(reflected_img)
Q5 - Write a computer program capable of performing the following intensity transformations to
enhance an image.

A) Image negative B) Log transformation C) Power law transformation D) Thresholding

#image negative

img_neg=cv2.bitwise_not(img)

plt.imshow(img_neg)

# Log Transformation

grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

c = 255/(np.log(1 + np.max(grayimg)))

print(c)

imglog = c*np.log(1+grayimg)

imglog = np.array(imglog, dtype = np.uint8)

plt.imshow(imglog)

#gamma Correction

gamma = 2 # less tham 0 lighter while more than 0 brighter.

imggamma = np.array(255*(img/255)** gamma, dtype =


np.uint8)

plt.imshow(imggamma)
#Thresholding

import cv2

import matplotlib.pyplot as plt

import os

import numpy as np

img1 = cv2.imread('/content/Mona.jpg')

ret, thresh1 = cv2.threshold(img1, 10, 100,


cv2.THRESH_BINARY_INV)

print(ret)

plt.imshow(thresh1)

Q6 - Write a computer program to perform the following spatial filtering operations o an image.

A) Box filter B) Weighted Averaging C) Gaussian filtering D) Median filtering

# Box filter

kernel = np.array([[1,1,1,1],[1,1,1,1],[1,1,1,1],
[1,1,1,1]])/9

dst = cv2.filter2D(img1, -1, kernel)

plt.imshow(dst)

plt.subplot(121), plt.imshow(img1), plt.title('original')

plt.subplot(122), plt.imshow(img1), plt.title('Averaging')

# Weighted Averaging

kernel = np.array([[1,2,1],[2,4,2],[1,2,1]])/16

dst = cv2.filter2D(img1, -1, kernel)

plt.imshow(dst)

plt.subplot(121), plt.imshow(img1), plt.title('original')


plt.subplot(122), plt.imshow(img1), plt.title('Averaging')

# GAUSSIAN FILTER

Gblur = cv2.GaussianBlur(img1,(5,5),21)

plt.imshow(img1)

# Median Blur - Best for Salt and Pepper noise

MedianPic = cv2.medianBlur(img1,5)

plt.imshow(MedianPic)

#BLUR IMAGE

blur = cv2.blur(img1, (5,5))

plt.imshow(img1)
Q7 - Write a program to enhance an image using Laplacian Filter.

#CODE

# Laplacian 1

kernel = np.array([[0,1,0],[1,-4,1],[0,1,0]])

dst = cv2.filter2D(img1, -1, kernel)

plt.imshow(dst)

plt.subplot(121), plt.imshow(img1),
plt.title('original')

plt.subplot(122), plt.imshow(dst),
plt.title('Laplacian')

sub = cv2.subtract(img1,dst)

plt.imshow(sub)

# Laplacian 2

kernel = np.array([[0,-1,0],[-1,4,-1],[0,-1,0]])

dst = cv2.filter2D(img1, -1, kernel)

plt.imshow(dst)

plt.subplot(121), plt.imshow(img1), plt.title('original')

plt.subplot(122), plt.imshow(dst), plt.title('Laplacian')

sub = cv2.subtract(img1,dst)

plt.imshow(sub)
Q8 - Write a program to sharpen an image using the unsharp masking technique.

#CODE

# Unmasking

kblur = cv2.blur(img1, (5,5))

sub = cv2.subtract(img1,kblur)

imgsharp = cv2.add(img1,sub)

plt.imshow(imgsharp)

Q9 - Write a computer program to calculate the histogram of an image.

#CODE

# HistoGram - GrayScale

grayimg = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)

hist = cv2.calcHist([grayimg], [0], None, [256], [0,256])

plt.hist(grayimg.ravel(), 256, [0,256]);

plt.show

#Histogram of a color image

color = ('b', 'g', 'r')

for i,col, in enumerate(color):

histr = cv2.calcHist([img1], [i], None, [256], [0,256])

plt.plot(histr,color = col)

plt.xlim([0,256])
Q10 - Write a computer program to Implement the Histogram Equalization technique.

#CODE

equ = cv2.equalizeHist(grayimg)

plt.hist(equ.ravel(),256,[0,256]);

plt.show()
LAB 11
Morphological operations
import cv2
import numpy as np

# Read the image in grayscale


img = cv2.imread('j.png', 0)
# Define a 5x5 kernel with all elements set to 1
kernel = np.ones((5, 5), np.uint8)
# Perform erosion on the image
erosion = cv2.erode(img, kernel, iterations=1)
# Perform dilation on the image
dilation = cv2.dilate(img, kernel, iterations=1)

ORIGNAL IMAGE EROSION IMAGE DILATION IMAGE

LAB 12
Edge Detection
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Read the image in grayscale
img = cv2.imread('img1.jpg', 0)
# Use the Canny edge detector
edges = cv2.Canny(img, 100, 200)
# Plot the original and edge images
plt.subplot(121), plt.imshow(img, cmap='gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(edges, cmap='gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
plt.show()

You might also like