Home Backend Development Python Tutorial Analyzing Emotion, Age, and Gender Using Serengil/DeepFace Library in Python

Analyzing Emotion, Age, and Gender Using Serengil/DeepFace Library in Python

Dec 31, 2024 pm 02:32 PM

In this article, we will discuss how to use Serengil's DeepFace library to analyze emotion, age, and gender from facial images. This article will include four main sections: (1) discussion of the libraries used, (2) how to use the libraries, (3) code explanation, and (4) analysis results.

1. Discussion of the DeepFace Library
DeepFace is a Python-based open-source library that offers facial analysis capabilities. This library was developed by Serengil and has become a powerful tool for many facial recognition and facial attribute analysis applications. DeepFace is able to detect and recognize faces, as well as analyze attributes such as emotion, age and gender with high accuracy.

DeepFace uses a machine learning model that has been trained on a large dataset of facial images. This model utilizes deep learning to extract facial features and perform attribute classification with precision. Some of the deep learning models used by DeepFace include VGG-Face, Google FaceNet, OpenFace, and many more. The ability to select and combine these models provides flexibility and reliability in a variety of application scenarios.

2. How to Use the Library
To use DeepFace, we need to install some dependencies first. Here are the detailed steps:

  • Make sure you have Python and pip installed on your system. You can check the installation by running the following command in the terminal:
python --version
pip --version
Copy after login
Copy after login
  • Install the DeepFace library with the following command:
pip install deepface
Copy after login
  • Apart from DeepFace, we also need other libraries such as OpenCV for image processing and NumPy for array manipulation. Install the library with the following command:
pip install opencv-python numpy
Copy after login

Once all the dependencies are installed, we are ready to start writing code to analyze faces.

3. Code Explanation
Here is the code to analyze emotion, age, and gender from facial images. This code consists of several main functions which will be explained in detail.

python
import json
import numpy as np
from deepface import DeepFace
import cv2

# Fungsi untuk menampilkan gambar
def show_image(img_path):
    img = cv2.imread(img_path)
    cv2.imshow("Image", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# Fungsi untuk konversi data agar bisa di-serialisasi
def convert_to_serializable(obj):
    if isinstance(obj, np.float32):
        return float(obj)
    raise TypeError(f"Object of type {type(obj)} is not JSON serializable")

# Fungsi untuk analisis wajah
def analyze_face(img_path):
    result = DeepFace.analyze(img_path)
    print("Hasil Analisis:", result)
    return result

# Fungsi utama
def main():
    # Path gambar
    img_path = "images/happy.jpg"

    # Analisis wajah
    analysis_result = analyze_face(img_path)

    # Simpan hasil analisis ke file JSON
    with open('result_analysis.json', 'w') as json_file:
        json.dump(analysis_result, json_file, default=convert_to_serializable)

if __name__ == "__main__":
    main()
Copy after login

Code Explanation
show_image(img_path): This function is used to display images using OpenCV. The image will be displayed in a separate window and wait for input from the user before closing the window.

convert_to_serializable(obj): This function converts a float32 numpy object to float so that it can be serialized to JSON format. This is necessary because numpy data types are not directly compatible with JSON.

analyze_face(img_path): Main function for analyzing faces. This function uses DeepFace to analyze the given face image and returns the analysis results.

main(): This function is the main entry point of the script. This function determines the image path, calls the face analysis function, and saves the analysis results to a JSON file.

img_path: Contains the image you want to analyze, an example of the image I used to analyze

Menganalisis Emosi, Umur, dan Gender Menggunakan Library Serengil/DeepFace di Python

4. Analysis Results
After running the above code using the image, you will get the facial analysis results saved in the result_analysis.json file. These results include information about the emotions, age, and gender of the analyzed faces. Here is an example of the result:

python --version
pip --version
Copy after login
Copy after login

With this information, you can understand more about the facial attributes analyzed using DeepFace. This library is very useful in various applications such as security, marketing, and research. For example, in the marketing field, emotional analysis can help in understanding consumer responses to advertising or products.

In addition, the ability to detect age and gender can be used in personalizing services, such as providing recommendations that match the user's profile. This article shows how powerful and flexible the DeepFace library is for facial analysis purposes.

The above is the detailed content of Analyzing Emotion, Age, and Gender Using Serengil/DeepFace Library in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles