Dip
Dip
Dip
INDEX
6 Detect a specific object using your webcam and also find the specific
pattern in an image
# Define the upper and lower boundaries for a color to be considered "Blue"
blueLower = np.array([100, 60, 60])
blueUpper = np.array([140, 255, 255])
bindex = 0
gindex = 0
rindex = 0
yindex = 0
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (0, 255, 255)]
colorIndex = 0
cv2.namedWindow('Paint', cv2.WINDOW_AUTOSIZE)
# Keep looping
while True:
# Grab the current paintWindow
(grabbed, frame) = camera.read()
frame = cv2.flip(frame, 1)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Determine which pixels fall within the blue boundaries and then blur
the binary image
blueMask = cv2.inRange(hsv, blueLower, blueUpper)
blueMask = cv2.erode(blueMask, kernel, iterations=2)
blueMask = cv2.morphologyEx(blueMask, cv2.MORPH_OPEN, kernel)
blueMask = cv2.dilate(blueMask, kernel, iterations=1)
bindex = 0
gindex = 0
rindex = 0
yindex = 0
paintWindow[67:,:,:] = 255
elif 160 <= center[0] <= 255:
colorIndex = 0 # Blue
elif 275 <= center[0] <= 370:
colorIndex = 1 # Green
elif 390 <= center[0] <= 485:
colorIndex = 2 # Red
elif 505 <= center[0] <= 600:
colorIndex = 3 # Yellow
else :
if colorIndex == 0:
bpoints[bindex].appendleft(center)
elif colorIndex == 1:
gpoints[gindex].appendleft(center)
elif colorIndex == 2:
rpoints[rindex].appendleft(center)
elif colorIndex == 3:
ypoints[yindex].appendleft(center)
# Append the next deque when no contours are detected (i.e., bottle cap
reversed)
else:
bpoints.append(deque(maxlen=512))
bindex += 1
gpoints.append(deque(maxlen=512))
gindex += 1
rpoints.append(deque(maxlen=512))
rindex += 1
ypoints.append(deque(maxlen=512))
yindex += 1
# Draw lines of all the colors (Blue, Green, Red and Yellow)
points = [bpoints, gpoints, rpoints, ypoints]
for i in range(len(points)):
for j in range(len(points[i])):
for k in range(1, len(points[i][j])):
if points[i][j][k - 1] is None or points[i][j][k] is None:
continue
cv2.line(frame, points[i][j][k - 1], points[i][j][k],
colors[i],
2) cv2.line(paintWindow, points[i][j][k - 1], points[i][j][k],
colors[i],
2)
OUTPUT:
PRACTICAL NO. 2
AIM:
Counting the circles and ellipses.
CODE:
import cv2
import numpy as np
# Load image
image = cv2.imread("blob.jpg", 0)
# Detect blobs
keypoints = detector.detect(image)
number_of_blobs = len(keypoints)
text = "Number of Circular Blobs: " + str(len(keypoints))
cv2.putText(blobs, text, (20, 550),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 100, 255), 2)
# Show blobs
cv2.imshow("Filtering Circular Blobs Only", blobs)
print(("Filtering Circular Blobs Only", number_of_blobs))
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT:
PRACTICAL NO. 3
AIM:
Display date and time while webcam is open on current video.
CODE:
import cv2
from datetime import datetime
# Open the Camera
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
# Put current DateTime on each frame
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,str(datetime.now()),(10,30), font,
1,(255,255,255),2,cv2.LINE_AA)
# Display the image
cv2.imshow('Mohan',img)
# wait for keypress
k = cv2.waitKey(10)
if k == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
OUTPUT:
PRACTICAL NO. 4
AIM:
Perform Image Processing Models such as follows:
a) Changing Color Space (BGR-HSV-GRAY, Masking on images).
CODE Of (a):
import cv2
import numpy as np
def nothing(x):
pass
cap = cv2.VideoCapture(0);
cv2.namedWindow("Tracking")
cv2.createTrackbar("LH", "Tracking", 0, 255, nothing)
cv2.createTrackbar("LS", "Tracking", 0, 255, nothing)
cv2.createTrackbar("LV", "Tracking", 0, 255, nothing)
cv2.createTrackbar("UH", "Tracking", 255, 255, nothing)
cv2.createTrackbar("US", "Tracking", 255, 255, nothing)
cv2.createTrackbar("UV", "Tracking", 255, 255, nothing)
while True:
#frame = cv2.imread('smarties.png')
_, frame = cap.read()
cv2.imshow("frame", frame)
cv2.imshow("mask", mask)
cv2.imshow("res", res)
key = cv2.waitKey(1)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()
OUTPUT Of (a):
b) Geometric Transformations of Images(Rotation, Affine Transformation, Perspective
Transformation)
Rotation
CODE:
import cv2 as cv
import matplotlib.pyplot as plt
img = cv.imread('messi5.jpg',0)
rows,cols = img.shape
# cols-1 and rows-1 are the coordinate limits.
M = cv.getRotationMatrix2D(((cols-1)/2.0,(rows-1)/2.0),90,1)
dst = cv.warpAffine(img,M,(cols,rows))
plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()
OUTPUT:
Affine Transformation
CODE:
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
img = cv.imread('messi5.jpg')
rows,cols,ch = img.shape
pts1 = np.float32([[50,50],[200,50],[50,200]])
pts2 = np.float32([[10,100],[200,50],[100,250]])
M = cv.getAffineTransform(pts1,pts2)
dst = cv.warpAffine(img,M,(cols,rows))
plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()
Output:
Perspective Transformation
CODE:
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
img = cv.imread('sudoku.png')
rows,cols,ch = img.shape
pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]])
pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])
M = cv.getPerspectiveTransform(pts1,pts2)
dst = cv.warpPerspective(img,M,(300,300))
plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()
OUTPUT:
c) Image Thresholding (SIMPLE Thresholding ,ADAPTIVE Thresholding).
SIMPLE Thresholding
CODE:
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('gradient.png',0)
ret,thresh1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
ret,thresh2 = cv.threshold(img,127,255,cv.THRESH_BINARY_INV)
ret,thresh3 = cv.threshold(img,127,255,cv.THRESH_TRUNC)
ret,thresh4 = cv.threshold(img,127,255,cv.THRESH_TOZERO)
ret,thresh5 = cv.threshold(img,127,255,cv.THRESH_TOZERO_INV)
titles = ['Original
Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
for i in range(6):
plt.subplot(2,3,i+1),plt.imshow(images[i],'gray',vmin=0,vmax=255)
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
OUTPUT:
ADAPTIVE Thresholding.
CODE:
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('sudoku.png',0)
img = cv.medianBlur(img,5)
ret,th1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
th2 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C,\
cv.THRESH_BINARY,11,2)
th3 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv.THRESH_BINARY,11,2)
titles = ['Original Image', 'Global Thresholding (v = 127)',
'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in range(4):
plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
OUTPUT:
d) Smoothing Images (Blur images with various low pass filters, Apply custom-made filters
to images (2D convolution)).
Blur images with various low pass filters.
CODE:
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('opencv-logo-white.png')
blur = cv.blur(img,(5,5))
blur = cv.GaussianBlur(img,(5,5),0)
blur = cv.medianBlur(img,55)
blur = cv.bilateralFilter(img,90,750,750)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(blur),plt.title('Blurred')
plt.xticks([]), plt.yticks([])
plt.show()
OUTPUT:
Blur:
Gaussian Blur:
Median Blur:
Bilateral Filter:
Apply custom-made filters to images (2D convolution)).
CODE:
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('opencv-logo.png')
kernel = np.ones((5,5),np.float32)/25
dst = cv.filter2D(img,-1,kernel)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(dst),plt.title('Averaging')
plt.xticks([]), plt.yticks([])
plt.show()
OUTPUT:
e) Morphological Transformations(Erosion, Dilation, Opening, Closing etc.).
CODE:
import cv2
import numpy as np
img = cv2.imread('j.png',0)
kernel = np.ones((5,5), np.uint8)
cv2.imshow('Input', img)
cv2.imshow('Erosion', img_erosion)
cv2.imshow('Dilation', img_dilation)
cv2.imshow('Opening', img_opening)
cv2.imshow('Closing', img_closing)
cv2.imwrite('Erosion.png', img_erosion)
cv2.imwrite('Dilation.png', img_dilation)
cv2.imwrite('Opening.png', img_opening)
cv2.imwrite('Closing.png', img_closing)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT:
Input:
Erosion:
Dilation:
Opening:
Closing:
f) Image Gradients(Sobel, Laplacian).
CODE:
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('sudoku.png',0)
laplacian = cv.Laplacian(img,cv.CV_64F)
sobelx = cv.Sobel(img,cv.CV_64F,1,0,ksize=5)
sobely = cv.Sobel(img,cv.CV_64F,0,1,ksize=5)
plt.subplot(2,2,1),plt.imshow(img,cmap = 'gray')
plt.title('Original'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,2),plt.imshow(laplacian,cmap = 'gray')
plt.title('Laplacian'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,3),plt.imshow(sobelx,cmap = 'gray')
plt.title('Sobel X'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,4),plt.imshow(sobely,cmap = 'gray')
plt.title('Sobel Y'), plt.xticks([]), plt.yticks([])
plt.show()
OUTPUT:
g) Canny Edge Detection.
CODE:
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('messi5.jpg',0)
edges = cv.Canny(img,100,200)
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()
OUTPUT:
PRACTICAL NO. 5
AIM:
Perform Object Detection and Object Tracking Using HSV Color Space.
Object Detection.
CODE:
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('person.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT:
Object Tracking Using HSV Color Space.
CODE:
import cv2
import numpy as np
def nothing(x):
pass
cv2.namedWindow("Tracking")
cv2.createTrackbar("LH", "Tracking", 0, 255, nothing)
cv2.createTrackbar("LS", "Tracking", 0, 255, nothing)
cv2.createTrackbar("LV", "Tracking", 0, 255, nothing)
cv2.createTrackbar("UH", "Tracking", 255, 255, nothing)
cv2.createTrackbar("US", "Tracking", 255, 255, nothing)
cv2.createTrackbar("UV", "Tracking", 255, 255, nothing)
while True:
frame = cv2.imread('smarties.png')
cv2.imshow("frame", frame)
cv2.imshow("mask", mask)
cv2.imshow("res", res)
key = cv2.waitKey(1)
if key == 27:
break
cv2.destroyAllWindows()
OUTPUT:
PRACTICAL NO. 6
AIM:
Detect a specific object using your webcam and also find the specific pattern in an image.
CODE:
import cv2
cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
cap.set(10, 70)
classNames = []
classFile = 'coco.names'
with open(classFile,'rt') as f:
classNames = f.read().rstrip('\n').split('\n')
configPath = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'
weightsPath = 'frozen_inference_graph.pb'
while True:
success, img = cap.read()
classIds, confs, bbox = net.detect(img, confThreshold=thres)
print(classIds, bbox)
if len(classIds) != 0:
for classId, confidence, box in zip(classIds.flatten(),
confs.flatten(), bbox):
cv2.rectangle(img, box, color=(0, 255, 0), thickness=2)
cv2.putText(img, classNames[classId - 1].upper(), (box[0] +
10, box[1] + 30),
cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
cv2.putText(img, str(round(confidence * 100, 2)), (box[0] +
200, box[1] + 30),
cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
cv2.imshow("Output", img)
cv2.waitKey(1)
OUTPUT:
PRACTICAL NO. 7
AIM:
Perform mouse Events (examples such as continuous line, display coordinates while left
mouse click, right mouse click display RGB Values).
Continuous Line:
CODE:
import numpy as np
import cv2
cv2.setMouseCallback('image',event_handling_for)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT:
Right and Left Mouse Click:
CODE:
import numpy as np
import cv2
cv2.setMouseCallback('image', click_event)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT:
PRACTICAL NO. 8
AIM:
Facial Recognition – Make your computer recognize you.
CODE:
import cv2
import sys
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
OUTPUT:
PRACTICAL NO. 9
AIM:
Perform GUI Features in an image (draw lines, rectangles, ellipses, circles ,arrow segment
line, put text).
CODE:
import numpy as np
import cv2
img = cv2.imread('lena.jpg', 1)
# img = np.zeros([512, 512, 3], np.uint8)
img = cv2.line(img, (0,0), (255,255), (147, 96, 44), 10) # 44, 96, 147
img = cv2.arrowedLine(img, (0,255), (255,255), (255, 0, 0), 10)
font = cv2.FONT_HERSHEY_SIMPLEX
img = cv2.putText(img, 'OpenCv', (10, 500), font, 4, (0, 255, 255), 10,
cv2.LINE_AA)
img = cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
img = cv2.polylines(img,[pts],True,(0,255,255))
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT:
PRACTICAL NO. 10
AIM:
Perform Basic operation on Image.
a) Access pixel values and modify them.
CODE:
import cv2
import numpy as np
img = cv2.imread('messi5.jpg')
px = img[100,100]
print(px)
blue = img[100,100,0]
print(blue)
img[100,100] = [255,255,255]
print(img[100,100])
OUTPUT:
b) Access image properties i.e., Shape.
c) Setting Region of Image (ROI).
d) Splitting and Merging images.
CODE:
import numpy as np
import cv2
img = cv2.imread('messi5.jpg')
print(img.shape)
print(img.size)
print(img.dtype)
b,g,r = cv2.split(img)
img = cv2.merge((b, g, r))
px = img[100,100]
print( px )
blue = img[100,100,0]
print( blue )
img[100,100] = [255,255,255]
print( img[100,100] )
cv2.imshow('imagewindow',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT:
e) Making Borders for Images.
CODE:
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
BLUE = [255,0,0]
img1 = cv.imread('opencv-logo.png')
replicate = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REPLICATE)
reflect = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REFLECT)
reflect101 = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REFLECT_101)
wrap = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_WRAP)
constant= cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_CONSTANT,value=BLUE)
plt.subplot(231),plt.imshow(img1,'gray'),plt.title('ORIGINAL')
plt.subplot(232),plt.imshow(replicate,'gray'),plt.title('REPLICATE')
plt.subplot(233),plt.imshow(reflect,'gray'),plt.title('REFLECT')
plt.subplot(234),plt.imshow(reflect101,'gray'),plt.title('REFLECT_101')
plt.subplot(235),plt.imshow(wrap,'gray'),plt.title('WRAP')
plt.subplot(236),plt.imshow(constant,'gray'),plt.title('CONSTANT')
plt.show()
OUTPUT:
f) Arithmetic Operation (Addition, Subtraction, Bitwise OR, Bitwise And).
Addition:
CODE:
import cv2
import numpy as np
img1 = cv2.imread('baboon.jpg',1)
img2 = cv2.imread('messi5.jpg',1)
cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT:
Subtraction:
CODE:
import cv2
import numpy as np
img1=cv2.imread('baboon.jpg')
img2=cv2.imread('messi5.jpg')
img2_resized = cv2.resize(img2, (img1.shape[1], img1.shape[0]))
OUTPUT:
Bitwise OR:
CODE:
import cv2
import numpy as np
img1=cv2.imread('baboon.jpg')
img2=cv2.imread('messi5.jpg')
OUTPUT:
Bitwise And:
CODE:
import cv2
import numpy as np
img1=cv2.imread('baboon.jpg')
img2=cv2.imread('messi5.jpg')
OUTPUT:
C) Image Blending.
CODE:
import cv2
import numpy as np
apple = cv2.imread('apple.jpg')
orange = cv2.imread('orange.jpg')
print(apple.shape)
print(orange.shape)
apple_orange = np.hstack((apple[:, :256], orange[:, 256:]))
cv2.imshow("apple", apple)
cv2.imshow("orange", orange)
cv2.imshow("apple_orange", apple_orange)
cv2.imshow("apple_orange_reconstruct", apple_orange_reconstruct)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT: