The error you encountered is because the datasets.ImageFolder class in PyTorch expects the images to be organized in a specific directory structure where each class of images is stored in its own subdirectory. Since you are probably working with a flat directory structure without subdirectories per class, you need to modify your approach slightly.
Here are two ways to address this issue:
- Modify the directory structure to comply with
datasets.ImageFolder.
- Create a custom dataset class.
Approach 1: Modify Directory Structure
If you want to stick with datasets.ImageFolder, you would need to place your images into a subdirectory, even if all images belong to the same class. Here's an example of the desired structure:
path_to_database_faces/
└── all_faces/
├── face1.jpg
├── face2.jpg
└── ...
Your code will look like this with the modified structure:
database_faces_dir = 'path_to_database_faces/all_faces/'
database_dataset = datasets.ImageFolder(root=database_faces_dir, transform=preprocess)
Approach 2: Create a Custom Dataset Class
If restructuring your directory is impractical, you can create a custom dataset:
import os
from torch.utils.data import Dataset
from PIL import Image
class CustomImageDataset(Dataset):
def __init__(self, image_dir, transform=None):
self.image_dir = image_dir
self.transform = transform
self.image_paths = [os.path.join(image_dir, img_name) for img_name in os.listdir(image_dir) if img_name.endswith(('.png', '.jpg', '.jpeg'))]
def __len__(self):
return len(self.image_paths)
def __getitem__(self, idx):
img_path = self.image_paths[idx]
image = Image.open(img_path).convert('RGB')
if self.transform:
image = self.transform(image)
return image, img_path
# Load database faces using CustomImageDataset
database_faces_dir = 'path_to_database_faces/'
database_dataset = CustomImageDataset(image_dir=database_faces_dir, transform=preprocess)
database_loader = data.DataLoader(database_dataset, batch_size=batch_size, shuffle=False, num_workers=workers)
# Store embeddings and filenames
embeddings = []
file_names = []
# Compute embeddings for database faces
for inputs, paths in database_loader:
inputs = inputs.to(device)
batch_embeddings = get_embedding(model_features, inputs, device)
embeddings.append(batch_embeddings)
file_names.extend(paths) # Collect the filenames for reference
# Convert embeddings list to array
embeddings_array = np.vstack(embeddings)
# Compare target face with database faces
similarities = [cosine_similarity(target_embedding, embed) for embed in embeddings_array]
# Find the most similar face
most_similar_idx = np.argmax(similarities)
most_similar_face = file_names[most_similar_idx]
most_similar_score = similarities[most_similar_idx]
print(f"Most similar face: {most_similar_face} with similarity score: {most_similar_score}")
Explanation
-
CustomImageDataset Class:
__init__: Initializes the dataset with the directory path and transforms.
__len__: Returns the number of images.
__getitem__: Loads and processes the image at the specified index.
-
Embedding Computation:
- Embeddings are computed in batches and stored in both the
embeddings list and their respective file paths in the file_names list.
-
Comparison:
- Similarities between the target and the database embeddings are computed and the most similar image is found.
Notes
- Purpose of
transform: Ensures that each image is processed similarly before passing through the model for embedding computation.
- Memory Management:
database_loader helps to efficiently process large datasets.
This custom dataset approach makes the script flexible to handle any flat directory structure without requiring changes to your dataset organization.