Last active
April 27, 2025 22:34
-
-
Save gauti123456/fa9810ffe028c13bed84c323e55ed715 to your computer and use it in GitHub Desktop.
Python 3 OpenCV & Deep AI Face Recognition & Analysis of Images and Save Result in JSON File
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from deepface import DeepFace | |
import cv2 | |
import os | |
import numpy as np # Add numpy | |
# Path to image | |
image_path = "angry.jpg" | |
# Verify if image exists | |
if not os.path.exists(image_path): | |
print(f"Error: {image_path} not found.") | |
exit() | |
# Load and show the image | |
img = cv2.imread(image_path) | |
cv2.imshow("Input Image", img) | |
cv2.waitKey(1) # Small delay | |
# Analyze the face | |
print("Analyzing face, please wait...") | |
result = DeepFace.analyze(img_path=image_path, actions=['age', 'gender', 'emotion', 'race'], enforce_detection=False) | |
# DeepFace returns a list sometimes; pick the first | |
if isinstance(result, list): | |
result = result[0] | |
# Extract precise information | |
# Safely convert np.float32 to float | |
def convert(obj): | |
if isinstance(obj, np.float32) or isinstance(obj, np.float64): | |
return float(obj) | |
return obj | |
analyzed_info = { | |
"Age": convert(result.get('age')), | |
"Gender": {k: convert(v) for k, v in result.get('gender', {}).items()}, | |
"Dominant Emotion": result.get('dominant_emotion'), | |
"Dominant Race": result.get('dominant_race') | |
} | |
# Display info nicely | |
print("\nAnalysis Result:") | |
for key, value in analyzed_info.items(): | |
print(f"{key}: {value}") | |
# Save to JSON file | |
output_file = "analysis_result.json" | |
with open(output_file, 'w') as f: | |
json.dump(analyzed_info, f, indent=4) | |
print(f"\nAnalysis saved to {output_file}") | |
# Cleanup | |
cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment