OpenCV

1. What is OpenCV ?
Open CV is an open source library for image processing . The application includes, face detection, objection tracking, land mark detection and more

2. What language does OpenCV use ?
Open CV uses multiple language such as C++ , phyton, java. However, it is preferable to use python. 

3. Prerequisite of OpenCV ?
a. Read and write image using OpenCV
b. Diffrerentiate color spaces present in OpenCV
c. Create NumPy array and familiar with the basic operation of NumPy

Pre-OpenCV 

1. Install the latest Python Software
Link: https://www.python.org/downloads/
(Note: At this time of learning, I'm using the 3.11 version)
2. Install Visual Studio Code 
Link: https://code.visualstudio.com/download 
3. Search "Command Prompt" on the device and install two packages
a. opencv-python module by typing the following in Command Prompt
pip install opencv-contrib-python
b. caer by typing the following in Command Prompt
pip install caer


Module 

Read images 
1. Create a folder in Document - "OpenCV"
Create two folders such as Videos and Photos and download few photos and videos in the Document folder
2. Go to Visual Code Studio 
Open the OpenCV folder
Create a new file - read.py 
3. Code 

import cv2 as cv

img = cv.imread('Photos/cat.jpg) // this reads the image

cv.imshow('cat',img) // this display the image 

cv.waitKey(0)

4. Run the code . Make sure Command prompt is used in the Terminal

Then type python read.py and the image will appear 



Read Video
Code 

import cv2 as cv
# img = cv.imread('Photos/cat1.jpeg')
# cv.imshow('Cat',img)
capture = cv.VideoCapture('Videos/Test Flight.mp4') # capture is variable . inside () - 1. a path to video file as the current code 2. as numbers can be assigned or inserted. Example : (1) - Camera/Webcam connected to laptop
while True:
    isTrue,frame = capture.read()# read video frame by frame
    cv.imshow('Video',frame) # display as individual frame
    if cv.waitKey(20) & 0xFF==ord('d'): #stop the video from play indefinately when d is pressed
        break # break while loop
capture.release ()
cv.destroyAllWindows()

2. Run the code
(Note : Press "d" to stop the video)

Resizing and Rescaling Image
import cv2 as cv
img = cv.imread('Photos/cat1.jpeg')
cv.imshow('Cat',img)
def rescaleFrame(frame, scale =0.75) :
     # create a function . 0.75 - resized to 75 percent
     # works for images,videos and live videos
    width = int (frame.shape[1] * scale) #  0 is width
    height = int (frame.shape[0] * scale) #  1 is height
    dimensions = (width,height)
    return cv.resize(frame,dimensions,interpolation = cv.INTER_AREA)
resized_image =rescaleFrame(img)
cv.imshow('Image',resized_image)
# def changeRes(width,height):
    #only for live videos
    #capture.set(3,width)
    #capture.set(4,height)
#read videos
capture = cv.VideoCapture('Videos/Test Flight.mp4') # capture is variable . inside () - 1. a path to video file as the current code 2. as numbers can be assigned or inserted. Example : (1) - Camera/Webcam connected to laptop
while True:
    isTrue,frame = capture.read()# read video frame by frame
    frame_resized = rescaleFrame(frame)
    cv.imshow('Video',frame) # display as individual frame
    cv.imshow('Video Resized', frame_resized)
    if cv.waitKey(20) & 0xFF==ord('d'): #stop the video from play indefinitely when d is pressed
        break # break while loop
capture.release ()
cv.destroyAllWindows()

Draw and Write on Images 

Code 1 : Display blank image

import cv2 as cv
import numpy as np

blank = np.zeros((500,500),dtype = 'uint8') #size of blank image
cv.imshow('Blank',blank)
img = cv.imread('Photos/cat1.jpeg')
cv.imshow('Cat',img)

cv.waitKey(0)

Code 2 : Paint the image a certain color
import cv2 as cv
import numpy as np

blank = np.zeros((500,500,3),dtype = 'uint8')#(height,width,number of colour channels) #size of blank image
cv.imshow('Blank',blank)

blank [:] = 0,255,0 # colour . Explore how to do this
cv.imshow('Green',blank)

cv.waitKey(0)

Code 3 : Draw a rectangle 
import cv2 as cv
import numpy as np

blank = np.zeros((500,500,3),dtype = 'uint8')#(height,width,number of colour channels) #size of blank image
cv.imshow('Blank',blank)

cv.rectangle(blank,(0,0),(250,250),(0,255,0), thickness = 2)
#(0,0) - origin
#(250,250) - end point
#(0,255,0) - green
#thickness = 2 - line thickness #thickness = cv.FILLED - to fill image with green #thickness = -1 - to fill image with green

cv.imshow('Rectangle',blank)

cv.waitKey(0)



Code 4: Draw a circle
import cv2 as cv
import numpy as np

blank = np.zeros((500,500,3),dtype = 'uint8')#(height,width,number of colour channels) #size of blank image
cv.imshow('Blank',blank)
cv.circle (blank,(250,250),40,(0,0,255) , thickness = 2)
#(250,250) - centre of frame
# 40 - radius
#(0,0,255) - red
#thickness = 2 - line thickness
cv.imshow('circle',blank)

cv.waitKey(0)


Code 4 - Draw line 
import cv2 as cv
import numpy as np

blank = np.zeros((500,500,3),dtype = 'uint8')#(height,width,number of colour channels) #size of blank image
cv.imshow('Blank',blank)
cv.line(blank,(0,250),(250,250),(255,255,255) , thickness = 2)
#(0,250) - origin
#(250,250) - end
#(255,255,255) - white
cv.imshow('line',blank)

cv.waitKey(0)

Code 5 - Write text 

import cv2 as cv
import numpy as np

blank = np.zeros((500,500,3),dtype = 'uint8')#(height,width,number of colour channels) #size of blank image
cv.imshow('Blank',blank)

cv.putText(blank,'Hello', (225,225), cv.FONT_HERSHEY_SCRIPT_COMPLEX,1.0,(0,255,0), thickness=2)
# 'Hello' - text
# (255,255) - coordinate of text
# cv.FONT - font
# 1.0 - scale
# (0,255,0) - color
# thickness = 2 - line thickness

cv.imshow('Text',blank)

cv.waitKey(0)

5 Essential Function

Code 1 : Converting image to gray scale

import cv2 as cv

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('cat1',img)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY) #cv.COLOR_BGR2GRAY- convert color (from)to(another color)
cv.imshow('Gray',gray)


cv.waitKey(0)

Code 2 : Blurring image

import cv2 as cv

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('cat1',img)

blur = cv.GaussianBlur(img,(3,3), cv.BORDER_DEFAULT)
# (3,3) - blurness . increase this and pic gets blurer
cv.imshow('Gray',blur)

cv.waitKey(0)

Code 3: Edge Cascade

import cv2 as cv

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('cat1',img)

canny =cv.Canny(img,125,175)
# 125.175 - threshhold value . change img to blur to reduce the amount of edges
cv.imshow ('Canny edges',canny)

cv.waitKey(0)

Result 


Code 4 : Dilate image

import cv2 as cv

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('cat1',img)

canny =cv.Canny(img,125,175)
# 125.175 - threshhold value
cv.imshow ('Canny edges',canny)

dilated = cv.dilate(canny,(7,7),iterations =3)
cv.imshow('cat1',dilated)

cv.waitKey(0)

Result


Code 5: Erode Image

import cv2 as cv

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('cat1',img)

canny =cv.Canny(img,125,175)
# 125.175 - threshhold value
cv.imshow ('Canny edges',canny)

dilated = cv.dilate(canny,(7,7),iterations =3)
cv.imshow('cat1',dilated)

eroded = cv.erode(dilated,(7,7),iterations =3)
cv.imshow('cat1',eroded)

cv.waitKey(0)

Result 

Code 5 : Resize and Crop

import cv2 as cv

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('cat1',img)

#Resize
resized = cv.resize(img,(500,500),interpolation =cv.INTER_CUBIC)
#(500,500) - destination size  or size of resizing
# cv.INTER_LINEAR - to scale to larger image
# cv.INTER_CUBIC - to scale to larger image with better quality
# cv.INTER_AREA - to shrink

cv.imshow('resized', resized)

cv.waitKey(0)


Code 6 : Crop (not verified)

import cv2 as cv

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('cat1',img)

#crop using array slicing
cropped = img[50 :200, 200:400]
#[50:200,200:400] - region to crop
cv.imshow('Cropped', cropped)

cv.waitKey(0)

Translating Image 

import cv2 as cv
import numpy as np

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('cat1',img)

#translation - shifting image along x -axis and y-axis
def translate(img,x,y):
    #(img,x,y) -  x and y represents number of pixels you want to shift along the x-axis and y-axis
    trasMat = np.float32([[1,0,x],[0,1,y]])
    #transMat - which is known as translation matrix is used to translate image
    dimensions = (img.shape[1], img.shape[0])
    # img.shape[1] - width
    # img.shape[0]- height
    return cv.warpAffine(img,trasMat,dimensions)

# -x -- Left
# -y -- Up
# x -- right
# y --Down

translated = translate(img, 100, 100)
# (img, 100, 100) - shifting right by 100 pixels and down by 100 pixels
cv.imshow('translated',translated)

cv.waitKey(0)

Rotation

import cv2 as cv
import numpy as np

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('cat1',img)

#rotation by some angle
def rotate (img,angle,rotPoint=None):
#rotation function
    (height,width) = img.shape[:2]

    if rotPoint is None:
        rotPoint = (width//2,height//2)
        #rotate around centre

    rotMat = cv.getRotationMatrix2D(rotPoint,angle,1.0)
    #rotMat - rotation matrics
    #(rotPoint,angle,1.0) - rotationpoint, angle, scale value
    dimensions = (width,height)

    return cv.warpAffine(img,rotMat,dimensions)

rotated = rotate(img,45)
cv.imshow('rotated',rotated)

rotated_rotated = rotate(rotated, -45)
#rotated_rotated = rotate(rotated,45) - rotated, rotated image
cv.imshow('rot',rotated_rotated)

cv.waitKey(0)

Fliping  image 

import cv2 as cv
import numpy as np

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('cat1',img)

#flip
flip = cv.flip(img,1)
# 0 - flipping image vertically (x-axis)
# 1 - flipping image horizontall (y-axis)
# -1 -flipping image both harizontally and vertically
cv.imshow('flip',flip)

cv.waitKey(0)

Contour Detection

- to find out how many contours are there

import cv2 as cv

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('Cats',img)

#contour detection - which are boundaries of object. contours and edges are two different things

gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
#convert image to grey scale
cv.imshow('gray', gray)

canny = cv.Canny(img,125,175)
#grab the edges
# (125,175) -threshold value
cv.imshow('canny',canny)

contours,hierarchies = cv.findContours(canny,cv.RETR_LIST,cv.CHAIN_APPROX_NONE)
#cv.(something as below) - mode to find contour
#cv.RETR_TREE - all hierarchical contour
#cv.RETR_EXTERNAL - external contour only
#cv.RETR_LIST - all contour
#cv.CHAIN_APPROX_NONE - contour approximation ; take all points
#cv.CHAIN_APPROX_SIMPLE - only takes end points
print(f'{len(contours)} contour(s) found')

cv.waitKey(0)

Result 

Finding edges by blurring image

import cv2 as cv

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('Cats',img)

#contour detection - which are boundaries of object. contours and edges are two different things

gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
#convert image to grey scale
cv.imshow('gray', gray)

#blur
blur =cv.GaussianBlur(gray,(5,5),cv.BORDER_DEFAULT)
cv.imshow('Blur',blur)

canny = cv.Canny(blur,125,175)
#grab the edges
# (125,175) -threshold value
cv.imshow('canny',canny)

contours,hierarchies = cv.findContours(canny,cv.RETR_LIST,cv.CHAIN_APPROX_SIMPLE)
#cv.(something as below) - mode to find contour
#cv.RETR_TREE - all hierarchical contour
#cv.RETR_EXTERNAL - external contour only
#cv.RETR_LIST - all contour
#cv.CHAIN_APPROX_NONE - contour approximation ; take all points
#cv.CHAIN_APPROX_SIMPLE - only takes end points
print(f'{len(contours)} contour(s) found')

cv.waitKey(0)

Result

Notice the number of contours reduced when blurred



Finding edges by threshold method

import cv2 as cv

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('Cats',img)

#contour detection - which are boundaries of object. contours and edges are two different things

gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
#convert image to grey scale
cv.imshow('gray', gray)

#threshold  - looks at image and binarize the image
ret,thresh = cv.threshold(gray,125,255,cv.THRESH_BINARY)
#gray - take it gray image
#125 - threshold value
# 255 - maximum value
# Below 125 - set to black
# Above 125 -  set white
#cv.THRESH_BINARY - to binarize image
cv.imshow('thresh', thresh)

contours,hierarchies = cv.findContours(thresh,cv.RETR_LIST,cv.CHAIN_APPROX_SIMPLE)
#cv.(something as below) - mode to find contour
#cv.RETR_TREE - all hierarchical contour
#cv.RETR_EXTERNAL - external contour only
#cv.RETR_LIST - all contour
#cv.CHAIN_APPROX_NONE - contour approximation ; take all points
#cv.CHAIN_APPROX_SIMPLE - only takes end points
print(f'{len(contours)} contour(s) found')

cv.waitKey(0)

Result



Drawing contour on a blank page
- can use blur or threshold method 
- use canny method first and then find the contour using that
- threshold method has disadvantage
import cv2 as cv
import numpy as np

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('Cats',img)

blank = np.zeros(img.shape, dtype ='uint8')
cv.imshow ('Blank', blank )

#contour detection - which are boundaries of object. contours and edges are two different things

gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
#convert image to grey scale
cv.imshow('gray', gray)
#threshold  - looks at image and binarize the image
ret,thresh = cv.threshold(gray,125,255,cv.THRESH_BINARY)
#gray - take it gray image
#125 - threshold value
# 255 - maximum value
# Below 125 - set to black
# Above 125 -  set white
#cv.THRESH_BINARY - to binarize image
cv.imshow('thresh', thresh)

contours,hierarchies = cv.findContours(thresh,cv.RETR_LIST,cv.CHAIN_APPROX_SIMPLE)
#cv.(something as below) - mode to find contour
#cv.RETR_TREE - all hierarchical contour
#cv.RETR_EXTERNAL - external contour only
#cv.RETR_LIST - all contour
#cv.CHAIN_APPROX_NONE - contour approximation ; take all points
#cv.CHAIN_APPROX_SIMPLE - only takes end points
print(f'{len(contours)} contour(s) found')

#drawing contour on blank image
cv.drawContours(blank,contours,-1, (0,0,255), 2)
# -1 - how many contours do we want, since we want all of them, its -1
# (0,0,255) - red
# 2 - thickness
cv.imshow('contours', blank)


cv.waitKey(0)

Result

Switch color spaces in OpenCV

1. convert BGR image to HSV
import cv2 as cv

img = cv.imread('Photos/car1.jpeg')
cv.imshow('cat1',img)

# convert BGR to HSV
# HSV - based on how huma think and conceive color
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
cv.imshow('hsv',hsv)

cv.waitKey(0)

Result


Code 2 : Convert BGR to Lab
import cv2 as cv

img = cv.imread('Photos/cat1.jpeg')
cv.imshow('cat1',img)

#convert BGR to Lab
lab = cv.cvtColor(img, cv.COLOR_BGR2Lab)
cv.imshow('lab', lab)

cv.waitKey(0)

Result


Code 3 : convert BGR to RGB
OpenCV reads image in BGR format
In real world(ourside of OpenCV), it uses the RGB format
import cv2 as cv
import matplotlib.pyplot as plt

img = cv.imread('photos/cat1.jpg')
cv.imshow('cat1', img)


#convert BGR to RGB
plt.imshow(img)
plt.show()

Result- RGB in open CV 

Code : Convert BGR to RGB in OpenCV
import cv2 as cv
import matplotlib.pyplot as plt

img = cv.imread('photos/cat1.jpg')
cv.imshow('cat1', img)

#convert BGR to Lab
lab = cv.cvtColor(img, cv.COLOR_BGR2Lab)
cv.imshow('lab', lab)

#BGR to RGB
rgb =cv.cvtColor(img,cv.COLOR_BGR2RGB)
cv.imshow('rgb',rgb)


plt.imshow(rgb)
plt.show()


cv.waitKey(0)

Result : RGB in Open CV

Result : RGB in Matplotlib (outside open cv)

Conversion can be done , but not directly from gray scale to HSV
To convert grayscale to HSV, convert grayscale to BGR, then BGR to HSV

Code : HSV to BGR 
import cv2 as cv
import matplotlib.pyplot as plt

img = cv.imread('photos/cat1.jpg')
cv.imshow('cat1', img)

hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
cv.imshow('HSV', hsv)

hsv_bgr = cv.cvtColor(hsv,cv.COLOR_HSV2BGR)
cv.imshow('HSV to BGR', hsv_bgr)

cv.waitKey(0)

Code : LAB to BGR

import cv2 as cv
import matplotlib.pyplot as plt

img = cv.imread('photos/cat1.jpg')
cv.imshow('cat1', img)

#convert BGR to Lab
lab = cv.cvtColor(img, cv.COLOR_BGR2Lab)
cv.imshow('lab', lab)

lab_bgr = cv.cvtColor(lab,cv.COLOR_LAB2BGR)
cv.imshow('lab to BGR', lab_bgr)

cv.waitKey(0)

Color Channels 
- How to split and merge color channels in OpenCV

Code 1 : Split BGR image to color components

import cv2 as cv
import numpy as np

img = cv.imread('photos/cat1.jpg')
cv.imshow('Cat1', img)

b,g,r = cv.split(img)
#cv.split (img) - splits the image to blue, green and red
cv.imshow('Blue',b)
cv.imshow('green', g)
cv.imshow ('red', r )

print (img.shape)
print(b.shape)
print (g.shape)
print(r.shape)

cv.waitKey(0)

Result 

Code 2 : Merge BGR image

import cv2 as cv
import numpy as np

img = cv.imread('photos/cat1.jpg')
cv.imshow('Cat1', img)

b,g,r = cv.split(img)
#cv.split (img) - splits the image to blue, green and red
cv.imshow('Blue',b)
cv.imshow('green', g)
cv.imshow ('red', r )

print (img.shape)
print(b.shape)
print (g.shape)
print(r.shape)

#merge image
merged = cv.merge([b,g,r])
cv.imshow('merged',merged)

cv.waitKey(0)

Code 3 : Extracting image as their colored components
import cv2 as cv
import numpy as np

img = cv.imread('photos/cat1.jpg')
cv.imshow('Cat1', img)

blank = np.zeros(img.shape[:2], dtype ='uint8')
#setting a blank component

b,g,r = cv.split(img)
#cv.split (img) - splits the image to blue, green and red

blue = cv.merge([b, blank,blank])
#setting the green and red components as blank (black)
green = cv.merge ([blank,g,blank])
red = cv.merge ([ blank, blank, r])

cv.imshow('Blue',blue)
cv.imshow('green', green)
cv.imshow ('red', red )

print (img.shape)
print(b.shape)
print (g.shape)
print(r.shape)

#merge image
merged = cv.merge([b,g,r])
cv.imshow('merged',merged)

cv.waitKey(0)

Result

Blurring Techniques

Code 1 : Smoothing image - caused by noise
import cv2 as cv

img = cv.imread('photos/cat1.jpg')
cv.imshow('Cat1', img)

#averaging - get average pixel intensity
average =cv.blur(img,(3,3)) #(3,3)-kernel size which have 3 row 3 column. higher kernel size more blur
cv.imshow('Average Blur', average)

cv.waitKey(0)


Code 2 - Gaussian blur
import cv2 as cv

img = cv.imread('photos/cat1.jpg')
cv.imshow('Cat1', img)

#gaussian blur - less blur
gauss = cv.GaussianBlur (img,(7,7),0)
cv.imshow('Gaussian Blur',gauss)

cv.waitKey(0)


Result 

Code 3 : Median Blur
import cv2 as cv

img = cv.imread('photos/cat1.jpg')
cv.imshow('Cat1', img)

#median blurring - not effetctive for high kernel size. more effective in reducing noise. instead of finding average it finds median
median = cv.medianBlur(img, 3) #assuming size 3X3
cv.imshow('Median Blur',median)

cv.waitKey(0)

Result 

Code 4 : Bilateral blurring
import cv2 as cv

img = cv.imread('photos/cat1.jpg')
cv.imshow('Cat1', img)

#Bilateral blurring - most effective .
bilateral = cv.bilateralFilter(img,5,15 ,15) #5 diameter, 15 colour sigma means more color, 15 space sigma means pixel further from central
cv.imshow('Bilateral',bilateral)
cv.waitKey(0)


Result


BITWISE Operator(and, or , not)
Operate in a binary manner
On - 1
Off - 0



BITWISE AND - takes in common image / intersecting region

blank = np.zeros ((400,400),dtype='uint8')
rectangle = cv.rectangle(blank.copy(),(30,30),(370,370),255,-1) # 30pixel, 255 white,-1 thickness
circle=cv.circle(blank.copy(),(200,200),200,255,-1) #200 centre, 200 radius 255 color,

cv.imshow('Rectangle',rectangle)
cv.imshow('Circle',circle)

#bitwise AND
bitwise_and=cv.bitwise_and(rectangle,circle)#
cv.imshow('BITWISEAND', bitwise_and)

cv.waitKey(0)



BITWISE OR - common region and not common and overlap / non intersecting and intersecting region
bitwise_or = cv.bitwise_or(rectangle,circle)
cv.imshow('Bitwise OR',bitwise_or)
cv.waitKey(0)


BITWISE XOR - non-intecting image 

bitwise_xor =cv.bitwise_xor(rectangle,circle)
cv.imshow('bitwise XOR',bitwise_xor)



Note : XOR -OR = AND
AND-OR =XOR

BITWISE (NOT)
bitwise_not =cv.bitwise_not(rectangle,circle)
cv.imshow('bitwise NOT', bitwise_not)

FACE DETECTION - haarcascade
- detection of face
- uses classifier -> present or not
- OPENCV uses predefined classifier -1. haarcascade 2. local binary pattern- advanced

1. Open haarcascade_frontalface_default_xml 
2. Click Raw > ctrl A > ctrl C
3. Create new file >name it "haar_face.xml" > paste the code > save  

1. FACE DETECTION - Number of faces
import cv2 as cv

img=cv.imread('Photos/tom4.jpeg')
cv.imshow ('tom',img)

#convert to grey scale
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.imshow('GRAY', gray)

haar_cascade =cv.CascadeClassifier ('haar_face.xml')
faces_rect = haar_cascade.detectMultiScale(gray,scaleFactor = 1.1, minNeighbors=3)

print (f'Number of faces = {len(faces_rect)}')
cv.waitKey(0)

RESULT 

2. Draw a rectangle over image 
#to draw a rectangle over the detected image
for(x,y,w,h) in faces_rect: #x,y,w,h >
    cv.rectangle(img,(x,y), (x+w,y+h), (0,255,0), thickness=2) #cv.rectangle draw rectangle, wyhw coordinate

cv.imshow('Detected faces', img)

RESULT 

GROUP PIC example

import cv2 as cv

img=cv.imread('Photos/g3.jpg')
cv.imshow ('g3',img)

#convert to grey scale
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.imshow('GRAY', gray)

haar_cascade =cv.CascadeClassifier ('haar_face.xml')
faces_rect = haar_cascade.detectMultiScale(gray,scaleFactor = 2.2, minNeighbors=3)

print (f'Number of faces = {len(faces_rect)}')

#to draw rectangle over detected image
for(x,y,w,h) in faces_rect: #x,y,w,h >
    cv.rectangle(img,(x,y), (x+w,y+h), (0,255,0), thickness=2) #cv.rectangel draw rectangle, wyhw coordinate

cv.imshow('Detected faces', img)
cv.waitKey(0)

RESULT


To increase accuracy increase the minimum neighbours
Pros/cons of haar cascade
1. Popular/not advanced
2. Les set up /Dealeds face recognizer
3. can be used for video

FACE RECOGNITION - with  OpenCV's built-in recognizer - train the recognizer
1. Safe at least 15 images of 3 types in a folder

import os
import cv2 as cv
import numpy as np

people =[ 'George Harrison, Ozil ']



RESULT






























































Comments