Python tutorial, reading and croping image, face detection, capturing image from video

April 06, 2022

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

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)

#To cropimage
def cropImage(image):
    img = cv2.imread(image)
    crop = img[50:180, 100:300]
    cv2.imshow("Image", image)
    cv2.imshow("Output", crop)

#To capture image from video
def captureImgFromVideo(video):
    frameWidth = 640
    frameHeight = 480
    cap = cv2.VideoCapture(video)
    success, image =
    img = cv2.resize(image, (frameWidth, frameHeight))
    cv2.imshow("Result", img)

#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)

# 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)

#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__':
      faceDetection("haarcascade_frontalface_default.xml", "man.jpg")