Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Open CV
  • scikit-image
  • pycairo
  • Pyglet
  • Python
  • Numpy
  • Pandas
  • Python Database
  • Data Analysis
  • ML Math
  • Machine Learning
  • NLP
  • Deep Learning
  • Deep Learning Interview Questions
  • ML Projects
  • ML Interview Questions
  • 100 Days of Machine Learning
Open In App
Next Article:
Cropping Faces from Images using OpenCV - Python
Next article icon

Cropping Faces from Images using OpenCV - Python

Last Updated : 03 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Opencv is a python library mainly used for image processing and computer vision. In this article first, we detect faces after that we crop the face from the image. Face detection is the branch of image processing that uses to detect faces.

We will use a pre-trained Haar Cascade model to detect faces from the image.  A haar cascade is the object detection method used to detect objects from the image. This algorithm was trained by numerous images. You can download the face haar cascade file by click here.

Let's Implementation in stepwise:

Step 1: In this step, we will read the image and converted it into grayscale.

Python3
import cv2  # Read the input image img = cv2.imread('mpw.jpeg')  # Convert into grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 

Explanation: In this code first we import our opencv library using import cv2. cv2.imread() method loads the image from the given path(ex:mpw.jpeg or filepath/mpw.jpeg) After loading the image we convert the image to a grayscale image using COLOR_BGR2GRAY.

Step 2: Use the Haar Cascade model to detect faces from the image.

Python3
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')  # Detect faces faces = face_cascade.detectMultiScale(gray, 1.1, 4) 

     

Explanation: We use cv2.CascadeClassifier for load haarcascade file in face_cascade. detectMultiScale() function used for detect faces.It takes 3 parameters:

  • Gray: input image(gray scale image)
  • 1.1: scale factor, it specifies how much the image size is reduced with each scale. It improves detection.
  • 4: MinNeighbours, specifies how many neighbors each candidate rectangle should have to retain.

Step 3: Find the face in the image.

Python3
for (x, y, w, h) in faces:     cv2.rectangle(img, (x, y), (x+w, y+h),                    (0, 0, 255), 2)          faces = img[y:y + h, x:x + w]     cv2.imshow("face",faces)     cv2.imwrite('face.jpg', faces)  cv2.imshow('img', img) cv2.waitKey() 

Explanation: x,y are pixel location of faces, w,h are width and height of faces. cv2.rectangle() function used for draw rectangle over the detected object, img is input image, (x,y),(x+w, y+h) are locations of rectangle,(0,0,255) is color of a rectangle this argument gets passed as a tuple for BGR,we would use (0,0,255) for red, 2 is thickness of rectangle.

Below is the full implementation:

Image Used - 

input image
Python3
import cv2  # Read the input image img = cv2.imread('mpw.jpeg')  # Convert into grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # Load the cascade face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')  # Detect faces faces = face_cascade.detectMultiScale(gray, 1.1, 4)  # Draw rectangle around the faces and crop the faces for (x, y, w, h) in faces:     cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)     faces = img[y:y + h, x:x + w]     cv2.imshow("face",faces)     cv2.imwrite('face.jpg', faces)      # Display the output cv2.imwrite('detcted.jpg', img) cv2.imshow('img', img) cv2.waitKey() 

Output:

Detected face
cropped image

Next Article
Cropping Faces from Images using OpenCV - Python

M

mohanapranes
Improve
Article Tags :
  • Python
  • OpenCV
  • Python-OpenCV
Practice Tags :
  • python

Similar Reads

    How to Blur Faces in Images using OpenCV in Python?
    Prerequisite: OpenCV OpenCV is a huge open-source library for computer vision, machine learning, and image processing.  It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as Numpy which is a highly optim
    2 min read
    Count number of Faces using Python - OpenCV
    Prerequisites: Face detection using dlib and openCV In this article, we will use image processing to detect and count the number of faces. We are not supposed to get all the features of the face. Instead, the objective is to obtain the bounding box through some methods i.e. coordinates of the face i
    3 min read
    Mapping coordinates from 3D to 2D using OpenCV - Python
    Mapping 3D coordinates to 2D coordinates is a common task in computer vision. This process involves transforming 3D points in a virtual space to their corresponding positions on a 2D image plane. In this article, we'll show you how to perform this task using OpenCV in Python programming. OpenCV is a
    6 min read
    Creating Hybrid Images Using OpenCV Library | Python
    Hybrid image, or "multi-scale image", is an exciting concept in computer vision. They are created by blending one image's high-frequency components with another's low-frequency components. The result is an image that appears as one when viewed from a distance but shows a different image when viewed
    4 min read
    Adding borders to the images using Python - OpenCV
    Image processing is an interesting field in today's era of Artificial Intelligence and Machine Learning. We can see the applications of image processing in our day-to-day life, like whenever we apply filter over any image (selfie) or when we want to apply some effect like blurring the image, etc.  I
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences