Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

Batch: IT-B4 CV (31711614) En No.

150160116096

Practical 1
Aim:-
(i) Write a python program to do calculator operation.
CODE
a = int(input("Enter 1st number: "))
b = int(input("Enter 2nd number: "))
op = input("Enter operator: ")
if op == "+":
print(a + b)
elif op == "-":
print(a -b)
elif op == "*" or op == "x":
print(a * b)
elif op == "/":
print(a / b)
OUTPUT

1|Page
Batch: IT-B4 CV (31711614) En No. 150160116096

(ii) Write a python program to print factorial of given number using for
loop

CODE
a = int(input(" Please a number : "))
fact = 1
for i in range(1, a + 1):
fact = fact * i
print("The factorial of %d = %d" %(a, fact))
OUTPUT

2|Page
Batch: IT-B4 CV (31711614) En No. 150160116096

(iii) Write a python program to print Fibonacci of given number


using while loop.

CODE
i=0
n1 = 0
n2 = 1
n = int(input("\nPlease Enter the Number: "))
while(i < n):
if(i <= 1):
Next = i
else:
Next = n1 + n2
n1 = n2
n2 = Next
print(Next)
i=i+1
OUTPUT

3|Page
Batch: IT-B4 CV (31711614) En No. 150160116096

(iv) Write a python program to print calendar and sub of date.

CODE
import calendar

yy = int(input("Enter year: "))

mm = int(input("Enter month: "))

print(calendar.month(yy,mm))
OUTPUT

4|Page
Batch: IT-B4 CV (31711614) En No. 150160116096

(v) Write a python program to print Fibonacci of given number


using function.

CODE
def fib(n):
a=0
b=1
if n == 1:
print(a)
else:
print(a)
print(b)
for i in range(2,n):
c=a+b
a=b
b=c
print(c)
fib(10)

OUTPUT

5|Page
Batch: IT-B4 CV (31711614) En No. 150160116096

Practical - 2

Aim : Implementing various basic image processing operations in


python/open-CV: Reading image, writing.

Code:

import cv2

path = "D:\\Photos\\background\\beach1.jpg"
# cv2.resizeWindow("op",400,300)
img = cv2.imread(path,1)
# cv2.namedWindow("output", cv2.WINDOW_NORMAL)
cv2.resizeWindow("op",100,50)

cv2.imshow("img",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

6|Page
Batch: IT-B4 CV (31711614) En No. 150160116096

Output:

7|Page
Batch: IT-B4 CV (31711614) En No. 150160116096

Practical 3
Aim: - Image, Conversion of image, and complement of image.
CODE
import cv2

path = "C:\\Users\\HP\\Desktop\\wallpaper\\abc.jpg"
img = cv2.imread(path,1)
CLR2GRAY = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("Color image",img)
cv2.imshow("Gray image",CLR2GRAY)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT

8|Page
Batch: IT-B4 CV (31711614) En No. 150160116096

CODE
import cv2

path = "C:\\Users\\HP\\Desktop\\wallpaper\\lion.jpg"
img = cv2.imread(path,1)
CLR2GRAY = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
threshold, BWIMG = cv2.threshold(CLR2GRAY,
127,255,cv2.THRESH_BINARY)
cv2.imshow("Black & White", BWIMG)
cv2.imshow("Color image", img)
cv2.imshow("gray image",CLR2GRAY)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT

9|Page
Batch: IT-B4 CV (31711614) En No. 150160116096

Practical - 4

Aim : Implement contrast adjustment of an image. Implement


Histogram processing and equalization.

Code:

import cv2

def BrightnessContrast(brightness=0):

brightness = cv2.getTrackbarPos("Brightness", "BEACH")

contrast = cv2.getTrackbarPos("Contrast", "BEACH")

effect = controller(img, brightness, contrast)

cv2.imshow("Effect", effect)

def controller(img, brightness=255, contrast=127):

brightness = int((brightness - 0) * (255 - (-255)) / (510 - 0) + (-255))


contrast = int((brightness - 0) * (127 - (-127)) / (254 - 0) + (-127))

if brightness != 0:
if brightness > 0:

10 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

shadow = brightness
max = 255
else:
shadow = 0
max = 255 + brightness

al_pha = (max - shadow) / 255


ga_mma = shadow

cal = cv2.addWeighted(img, al_pha, img, 0, ga_mma)


else:
cal = img

if contrast != 0:
Alpha = float(131 * (contrast + 127)) / (127 * (131 - contrast))
Gamma = 127 * (1-Alpha)
cal = cv2.addWeighted(cal, Alpha, cal, 0, Gamma)

cv2.putText(cal, 'B:{}, C:{}'.format(brightness, contrast), (10,30),


cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255),2)
return cal

img_path = "D:\\Photos\\background\\beach1.jpg"
original = cv2.imread(img_path)

img = original.copy()
cv2.namedWindow("BEACH")
11 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

cv2.imshow("BEACH", original)
cv2.createTrackbar("Brightness", "BEACH", 255,
2*255,BrightnessContrast)
cv2.createTrackbar("Contrast", "BEACH", 127, 2*127,BrightnessContrast)

BrightnessContrast(0)

cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

Code:

import cv2

import numpy as np

12 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

img_path = "D:\\Photos\\background\\beach1.jpg"
img = cv2.imread(img_path,0)
equ = cv2.equalizeHist(img)
res = np.hstack((img, equ))

cv2.imshow("D:\\Photos\\background\\",res)

cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

13 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Practical – 5

Aim : Implement the various low pass and high pass filtering
mechanisms.

Code:

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

path = "D:\\Photos\\background\\beach1.jpg"
img = cv2.imread(path)

kernel = np.ones((5,5), np.float32)/25


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

plt.subplot(121),plt.imshow(img),plt.title("Original")
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(img),plt.title("Averaging")
plt.xticks([]),plt.yticks([])
plt.show()

14 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Output:

Code:

import cv2
import numpy as np
from scipy import ndimage

kernel_3x3 = np.array([
[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1],
])

15 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

kernel_5x5 = np.array([
[-1, -1, -1, -1, -1],
[-1, 1, 2, 2, -1],
[-1, 2, 4, 2, -1],
[-1, 1, 2, 1, -1],
[-1, -1, -1, -1, -1],
])

path = "D:\\Photos\\background\\beach1.jpg"

img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Kern3 = ndimage.convolve(img, kernel_3x3)


kern5 = ndimage.convolve(img, kernel_5x5)

blurred = cv2.GaussianBlur(img, (11, 11), 0)


ghpf = img - blurred

cv2.imshow("3X3", Kern3)
cv2.imshow("5X5", kern5)
cv2.imshow("g_hpf", ghpf)
cv2.waitKey(0)
cv2.destroyAllWindows()

16 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Output:

17 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Practical - 6

Aim : image, conversion of images, and complement of an image.

Code:

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

path = "D:\\Photos\\background\\beach1.jpg"
img = cv2.imread(path,0)

f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)

magnitude_spectrum = 20*np.log(np.abs(fshift))

plt.subplot(121),plt.imshow(img,cmap='gray')
plt.title('Input Image'), plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(magnitude_spectrum,cmap='gray')
plt.title('Magnitude Image'), plt.xticks([]),plt.yticks([])
plt.show()

18 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Output:

19 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Practical - 7

Aim : Utilization of SIFT and HOG features for image analysis.

Code:

from skimage import feature


import cv2
import matplotlib.pyplot as plt

path = "D:\\Photos\\background\\beach1.jpg"
img = cv2.imread(path,1)

(hog, hog_image) = feature.hog(img, orientations=9,pixels_per_cell =


(8,8), cells_per_block=(2,2),block_norm='L2-Hys', visualize=True,
transform_sqrt=True)

cv2.imshow("Ori", img)
cv2.imshow('HOG IMAGE', hog_image)
# cv2.imwrite('hog_im', hog_image*255)
cv2.waitKey(0)

20 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Output:

Code:

import cv2
path = "D:\\Photos\\background\\beach1.jpg"
img = cv2.imread(path,1)
gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

sift = cv2.xfeatures2d.SIFT_create()
kp = sift.detect(gray, None)

img=cv2.drawKeypoints(gray ,kp ,img ,flags=cv2.DRAW_MATCHES_F


LAGS_DRAW_RICH_KEYPOINTS)

cv2.imwrite('image-with-keypoints.jpg', img)

21 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Output:

22 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Practical - 8

Aim : Performing/Implementing image segmentation.

Code:

from skimage.color import rgb2gray


import numpy as np
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
from scipy import ndimage

image = plt.imread("D:\\Photos\\background\\beach1.jpg")
image.shape
plt.imshow(image)

gray = rgb2gray(image)
plt.imshow(gray, cmap='gray')
gray.shape
gray_r = gray.reshape(gray.shape[0]*gray.shape[1])
for i in range(gray_r.shape[0]):
if gray_r[i] > gray_r.mean():
gray_r[i] = 1
else:
gray_r[i] = 0

23 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

gray = gray_r.reshape(gray.shape[0],gray.shape[1])
plt.imshow(gray, cmap='gray')
Output:

Code:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from scipy import ndimage
from skimage.color import rgb2gray

image = plt.imread("D:\\Photos\\background\\beach1.jpg")
plt.imshow(image)

24 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

gray = rgb2gray(image)

sobel_horizontal = np.array([np.array([1, 2, 1]), np.array([0, 0, 0]),


np.array([-1, -2, -1])])
sobel_vertical = np.array([np.array([-1, 0, 1]), np.array([-2, 0, 2]),
np.array([-1, 0, 1])])

out_h = ndimage.convolve(gray, sobel_horizontal, mode='reflect')


out_v = ndimage.convolve(gray, sobel_vertical, mode='reflect')

plt.imshow(out_h, cmap='gray')
plt.imshow(out_h, cmap='gray')
Output:

25 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Practical - 9

Aim : Implement optical flow computation algorithm.

Code:

import cv2 as cv
import numpy as np

cap = cv.VideoCapture("D:\\carvids.webm")
ret, first_frame = cap.read()

prev_gray = cv.cvtColor(first_frame, cv.COLOR_BGR2GRAY)


mask = np.zeros_like(first_frame)
mask[..., 1] = 255

while(cap.isOpened()):
ret, frame = cap.read()
cv.imshow("input", frame)
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
flow = cv.calcOpticalFlowFarneback(prev_gray, gray,None,0.5, 3,
15, 3, 5, 1.2, 0)
magnitude, angle = cv.cartToPolar(flow[..., 0], flow[..., 1])
mask[..., 0] = angle * 180 / np.pi / 2
mask[..., 2] = cv.normalize(magnitude, None, 0, 255,
cv.NORM_MINMAX)
rgb = cv.cvtColor(mask, cv.COLOR_HSV2BGR)

26 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

cv.imshow("dense optical flow", rgb)


prev_gray = gray
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()
Output:

27 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Practical - 10

Aim : Demonstrate the use of optical flow in any image processing


application.

Code:

import numpy as np
import cv2

cap = cv2.VideoCapture('D:\\data_slow.flv')

ret, frame1 = cap.read()


prvs = cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY)
hsv = np.zeros_like(frame1)
hsv[...,1] = 255

while(1):
ret, frame2 = cap.read()
next = cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY)

flow = cv2.calcOpticalFlowFarneback(prvs,next, None, 0.5, 3, 15, 3, 5,


1.2, 0)

mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])


hsv[...,0] = ang*180/np.pi/2

28 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

hsv[...,2] = cv2.normalize(mag,None,0,255,cv2.NORM_MINMAX)
rgb = cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR)

cv2.imshow('frame2',rgb)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
elif k == ord('s'):
cv2.imwrite('opticalfb.png',frame2)
cv2.imwrite('opticalhsv.png',rgb)
prvs = next

cap.release()
cv2.destroyAllWindows()
Output:

29 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Practical - 11
Aim : Object detection and Recognition on available online image
datasets.
Code:

from imageai.Detection import ObjectDetection

detector = ObjectDetection()

model_path = "yolo-tiny.h5"
input_path = "cars.jpg"
output_path = "output_image.jpg"

detector.setModelTypeAsTinyYOLOv3()
detector.setModelPath(model_path)
detector.loadModel()
detection = detector.detectObjectsFromImage(input_image=input_path,
output_image_path=output_path)

for eachItem in detection:


print(eachItem["name"] , " : ", eachItem["percentage_probability"])

Output:

30 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

31 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Practical - 12
Aim : Character or digit or face classification project.

Code:

import cv2
import os

cascPath=os.path.dirname(cv2. file )+"/data/haarcascade_frontalface_


default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)

video_capture = cv2.VideoCapture("D:\\PeopleWalking.mp4")

while True:
# Capture frame-by-frame
ret, frames = video_capture.read()

gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)

faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),

32 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

flags=cv2.CASCADE_SCALE_IMAGE
)

# Draw a rectangle around the faces


for (x, y, w, h) in faces:
cv2.rectangle(frames, (x, y), (x+w, y+h), (0, 255, 0), 2)

# Display the resulting frame


cv2.imshow('Video', frames)

if cv2.waitKey(1) & 0xFF == ord('q'):


break
video_capture.release()
cv2.waitKey(0)
cv2.destroyAllWindows()

33 | P a g e
Batch: IT-B4 CV (31711614) En No. 150160116096

Output:

34 | P a g e

You might also like