anti_spoofing / anti_spoofing.py
brxerq's picture
Update anti_spoofing.py
c59fa34 verified
raw
history blame
2.39 kB
import gradio as gr
import cv2
import dlib
import numpy as np
from skimage import feature
# Initialize your AntiSpoofingSystem class as previously defined
class AntiSpoofingSystem:
def __init__(self):
self.detector = dlib.get_frontal_face_detector()
self.predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
self.EAR_THRESHOLD = 0.25
def calculate_ear(self, eye):
A = np.linalg.norm(eye[1] - eye[5])
B = np.linalg.norm(eye[2] - eye[4])
C = np.linalg.norm(eye[0] - eye[3])
return (A + B) / (2.0 * C)
def analyze_texture(self, face_region):
gray_face = cv2.cvtColor(face_region, cv2.COLOR_BGR2GRAY)
lbp = feature.local_binary_pattern(gray_face, P=8, R=1, method="uniform")
lbp_hist, _ = np.histogram(lbp.ravel(), bins=np.arange(0, 58), range=(0, 58))
lbp_hist = lbp_hist.astype("float")
lbp_hist /= (lbp_hist.sum() + 1e-5)
return np.sum(lbp_hist[:10]) > 0.3
def process_image(self, image):
# Convert the image to grayscale and detect faces
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = self.detector(gray)
# If no face is detected, return a message
if len(faces) == 0:
return "No face detected. Please try again."
# Process the first detected face
face = faces[0]
landmarks = self.predictor(gray, face)
leftEye = np.array([(landmarks.part(n).x, landmarks.part(n).y) for n in range(36, 42)])
rightEye = np.array([(landmarks.part(n).x, landmarks.part(n).y) for n in range(42, 48)])
ear_left = self.calculate_ear(leftEye)
ear_right = self.calculate_ear(rightEye)
# Determine if a blink is detected
blink_detected = (ear_left < self.EAR_THRESHOLD and ear_right < self.EAR_THRESHOLD)
return "Blink detected!" if blink_detected else "No blink detected."
# Define the Gradio interface
anti_spoofing_system = AntiSpoofingSystem()
def detect_blink(image):
result = anti_spoofing_system.process_image(image)
return result
iface = gr.Interface(
fn=detect_blink,
inputs=gr.Image(shape=(720, 1280)),
outputs="text",
title="Anti-Spoofing Detection System",
description="Upload an image with a face to detect if a blink is detected."
)
# Launch the Gradio interface
iface.launch()