More Deep Learning Projects…

Project 7: Deepfake Detection with Deep Learning

In this article, I will take you through Deepfake Detection with Python and machine learning. I recently wrote an article on what a Deepfake is and how dangerous it is. If you do not know what a Deepfake is, I suggest you take a quick look at my previous article here before you get your hands dirty with the task of Deepfake detection with Python and machine learning.

Deepfake detection with Python

There have been many reports of fake videos of celebrities or famous politicians. These fake videos are hard to detect with the naked eye and have become a major problem in society.

Experience so far shows that Deepfake videos spread easily on platforms such as Facebook, Twitter and YouTube. As these platforms work on solving this problem, Facebook is making a large investment ($10 million) to fix it, and other platforms such as Twitter and Google are also working on it.

So detecting deepfakes is not an easy task. In this article, we will see how to tell fakes from real ones. It involves analyzing the videos frame by frame, detecting the faces in the real and fake videos, and cropping and analyzing the faces.

Deepfake detection in action

Let's now see how we can detect Deepfake content with Python and machine learning. I will start this task by importing the necessary libraries:

import numpy as np
import matplotlib.pyplot as plt
import cv2
import pandas as pd
import glob2
import os, fnmatch
from pathlib import Path
# import mtcnn
from mtcnn.mtcnn import MTCNN

Now suppose we have two videos, one real and one fake, and we want to detect which of the two is fake. That is essentially what we need to do in a Deepfake detection task.

Now I will create a function to process both videos:

def extract_multiple_videos(intput_filenames, image_path_infile):
    """Extract video files into sequence of images."""
i = 1  # Counter of first video
# Iterate file names:
    cap = cv2.VideoCapture('your_video_file_path.avi' or intput_filenames)
if (cap.isOpened()== False):
        print("Error opening file")
# Keep iterating break
    while True:
        ret, frame = cap.read()  # Read frame from first video
            
        if ret:
            cv2.imwrite(os.path.join(image_path_infile , str(i) + '.jpg'), frame)  # Write frame to JPEG file (1.jpg, 2.jpg, ...)
# you can uncomment this line if you want to view them.
#           cv2.imshow('frame', frame)  # Display frame for testing
            i += 1 # Advance file counter
        else:
            # Break the interal loop when res status is False.
            break
cv2.waitKey(50) #Wait 50msec
cap.release()

Calling the function

extract_multiple_videos(fake_video_name, fake_image_path_for_frame)
extract_multiple_videos(real_video_name, real_image_path_for_frame)

Now, after running the function, we will be able to read the videos and process them for the Deepfake detection task. Let's now see how we can identify a deepfake by comparing the two videos:

from skimage import measure
def mse(imageA, imageB):
    # the 'Mean Squared Error' between the two images is the
    # sum of the squared difference between the two images;
    # NOTE: the two images must have the same dimension
    err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
    err /= float(imageA.shape[0] * imageA.shape[1])
# return the MSE, the lower the error, the more "similar"
    # the two images are
    return err
def compare_images(imageA, imageB, title):
    # compute the mean squared error and structural similarity
    # index for the images
    m = mse(imageA, imageB)
    s = measure.compare_ssim(imageA, imageB)
    # setup the figure
    fig = plt.figure(title)
    plt.suptitle("MSE: %.2f, SSIM: %.2f" % (m, s))
    # show first image
    ax = fig.add_subplot(1, 2, 1)
    plt.imshow(imageA, cmap = plt.cm.gray)
    plt.axis("off")
    # show the second image
    ax = fig.add_subplot(1, 2, 2)
    plt.imshow(imageB, cmap = plt.cm.gray)
    plt.axis("off")
    # show the images
    plt.show()

In the code above, we compare the images extracted from the original video with the corresponding image from the fake videos. In the last section of the code, I checked whether there are any differences between the two images.

Output:

This is how we can detect deepfake files by comparing the original and fake files. I hope you liked this article on Deepfake detection with Python and deep learning.

Post links

One comment

Leave a comment

Your email address will not be published. Required fields are marked *