turns-00026.parquet:1504
22bc96b70537fa5e31b6cf17
turn 3/5gpt-4o-2024-05-13EnglishIndia435 words
degenerate_repetitionAbsentFinal dense release
USER
design a python program that is given input a image and the program recognizes all the faces and stores their embeddings
ASSISTANT
Certainly! Below is a Python program that takes an image as input, detects all the faces in the image using MTCNN, extracts their embeddings using the InceptionResnetV1 model, and stores these embeddings into individual `.npy` files. This program does not associate the embeddings with specific names but stores them with unique filenames to be retrieved or processed later.
Please make sure you have the required packages installed:
```sh
pip install torch torchvision facenet-pytorch numpy pillow
```
Here is the code:
```python
import os
import uuid
import torch
import numpy as np
from facenet_pytorch import InceptionResnetV1, MTCNN
from PIL import Image
# Initialize models
mtcnn = MTCNN(image_size=160, margin=0)
model = InceptionResnetV1(pretrained='vggface2').eval()
# Create a folder to store face embeddings
if not os.path.exists('embeddings'):
os.makedirs('embeddings')
# Function to extract face embeddings
def get_embeddings(img_path):
img = Image.open(img_path)
boxes, _ = mtcnn.detect(img)
if boxes is None:
return []
embeddings = []
for box in boxes:
# Convert the box coordinates to integers
box = [int(coord) for coord in box]
img_cropped = mtcnn.extract(img, box)
# Compute the embedding
embedding = model(img_cropped.unsqueeze(0)).detach().numpy()[0]
embeddings.append(embedding)
return embeddings
# Function to save embeddings
def save_embeddings(embeddings):
for embedding in embeddings:
# Generate a unique filename using uuid
filename = str(uuid.uuid4()) + '.npy'
np.save(f'embeddings/{filename}', embedding)
print(f'Embedding stored in embeddings/{filename}')
# Main function to process an image
def process_image(img_path):
embeddings = get_embeddings(img_path)
if not embeddings:
print("No faces detected.")
else:
save_embeddings(embeddings)
print(f'Total faces detected and saved: {len(embeddings)}')
# Example usage
image_path = r"C:\Users\divyr\OneDrive\Pictures\Camera Roll\WIN_20240525_12_56_27_Pro.jpg"
process_image(image_path)
# Any additional image can be processed similarly
# process_image(r"path_to_another_image.jpg")
```
### Explanation:
- **Model Initialization**:
- `mtcnn` and `model` are used for face detection and embedding extraction respectively.
- **Create "embeddings" Directory**:
- Check if the 'embeddings' directory exists; if not, create it.
- **get_embeddings Function**:
- Takes an image path as input, and uses `mtcnn` to detect faces and extract their embeddings. It converts the bounding box coordinates to integers before cropping.
- **save_embeddings Function**:
- Takes a list of embeddings and saves each embedding to a file with a unique name generated using `uuid`.
- **process_image Function**:
- Orchestrates the process of loading an image, getting the embeddings, and saving them. It reports the number of faces detected and saved.
- **Example Usage**:
- Modify `image_path` to your actual image path and call `process_image` to process the image and store face embeddings.
This program will help you to capture face embeddings from an image containing multiple faces, and store those embeddings for later use, such as face recognition, clustering, etc.