In this article i will explain you how you can read and crop an image, read image from video, detect face using open cv
Step 1: Install necessary python library which gonna help in reading images
- OpenCv: This is open source image recogntion library in python
pip3 install opencv-python
Step 2: For face detection you would need another xml file other than image
Download haarcascades file for face detection from this link https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
Step 2: Once the needed library installed copy paste the following code
import cv2
import numpy as np
#To read image and output
def readImage(image):
img = cv2.imread(image)
cv2.imshow("Image",img)
cv2.waitKey(0)
#To cropimage
def cropImage(image):
img = cv2.imread(image)
crop = img[50:180, 100:300]
cv2.imshow("Image", image)
cv2.imshow("Output", crop)
cv2.waitKey(0)
#To capture image from video
def captureImgFromVideo(video):
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(video)
success, image = cap.read()
img = cv2.resize(image, (frameWidth, frameHeight))
cv2.imshow("Result", img)
cv2.waitKey(0)
#To convert image to gray
def convertImage(image):
import cv2
img = cv2.imread(image)
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray Image", imgGray)
cv2.waitKey(0)
# For detecting face in an image
def faceDetection(cascade_qulifier, image):
face_Cascade = cv2.CascadeClassifier(cascade_qulifier)
image = cv2.imread(image)
imgGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_Cascade.detectMultiScale(imgGray, 1.1, 4)
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow("Result", image)
cv2.waitKey(0)
#main code here you can uncomment the function and pass the required argument in function
#keep the files such as image and video in same directory as this code is
if __name__ == '__main__':
"""readImage("man.jpg")"""
"""captureImgFromVideo("sample-mp4-file.mp4")"""
"""convertImage("man.jpg")"""
faceDetection("haarcascade_frontalface_default.xml", "man.jpg")
"""cropImage("man.jpg")"""