def getembeddings(imgpath): img = Image.open(imgpath) boxes, = mtcnn.detect(img) if…
- User
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 = img.crop(box) img_cropped = img_cropped.resize((160, 160)) # Resize to the input size required by the model img_cropped = torch.from_numpy(np.array(img_cropped)).permute(2, 0, 1).float() / 255.0 if img_cropped.ndimension() == 3: img_cropped = img_cropped.unsqueeze(0) # Compute the embedding embedding = model(img_cropped).detach().numpy()[0] embeddings.append(embedding) return embeddingsin this return embeddings is a list instead i want a numpy array
- Assistant
To return the embeddings as a NumPy array instead of a list, you can convert the list to a NumPy array at the end of your function. Here’s how you can do it:
- Import the necessary libraries if you haven't already (NumPy in this case).
- At the end of your function, use
np.arrayto convert the list of embeddings to a NumPy array.
Here's the modified function:
- User
.detach().numpy()[0] what does this do to a torch tensor
- Assistant
- User
how to apply cosine similarity between two embeddings
- Assistant
- User
def get_embeddingf(img_path): img = Image.open(img_path) img_cropped = mtcnn(img) embedding = model(img_cropped.unsqueeze(0)) return embedding in this return all the faces
- Assistant
- User
return tensors only
- Assistant
- User
embeddings.shape # torch.Size([11, 1, 512]) embedding1.shape # torch.Size([1, 512]) now embeddings has embiddings of 11 different faces, so check for most similar using similarity = torch.nn.functional.cosine_similarity(embedding1, embedding2) print(f'Similarity: {similarity.item()}')
- Assistant
- User
how to store all the tensors of 11 faces with different 11 names starting from index 00001 till 00011 in embeddings directory
- Assistant
- User
embeddings4 = get_embedding0(r"C:\Users\divyr\OneDrive\Pictures\Camera Roll\WIN_20240525_12_56_27_Pro.jpg") suppose i have this embeddings4 now all the embeddings of different students are stored in embeddings directory in pt file, now what i want is a code that checks all cosine_similarity and prints the most similar face file name
- Assistant
- User
now make a function that takes input a directory and embeddings having dimension x,1,512 containing the faces of x different students , now it checks each students' face with each file ending with .pt and prints attendance with file name
- Assistant
- User
RuntimeError Traceback (most recent call last) Cell In[40], line 45 43 # Example usage - assuming embeddings4 is the tensor with the students' embeddings 44 embeddings4 = get_embeddingsx(r"C:\Users\divyr\OneDrive\Pictures\Camera Roll\WIN_20240525_12_56_27_Pro.jpg") ---> 45 mark_attendance(embeddings4, directory='embeddings')
Cell In[40], line 29 26 file_path = os.path.join(directory, file) 27 saved_embedding = torch.load(file_path) ---> 29 similarity_score = calculate_cosine_similarity(student_embedding, saved_embedding) 31 if similarity_score > max_similarity: 32 max_similarity = similarity_score
Cell In[40], line 10 8 # Compute cosine similarity 9 similarity = torch.nn.functional.cosine_similarity(embedding1, embedding2, dim=0) ---> 10 return similarity.item()
RuntimeError: a Tensor with 512 elements cannot be converted to Scalar
- Assistant
- User
what does squeeze(0) function do
- Assistant
The
squeeze()function in PyTorch is used to remove dimensions of size from a tensor. The argument in specifies the particular dimension to be squeezed. If the specified dimension is of size , it will be removed. Otherwise, the tensor remains unchanged. - User
embeddings[11] = embeddings1 { "name": "IndexError", "message": "index 11 is out of bounds for dimension 0 with size 11", "stack": "--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[56], line 1 ----> 1 embeddings[11] = embeddings1
IndexError: index 11 is out of bounds for dimension 0 with size 11" }
- Assistant
- User
make a function that takes a list of embeddings and returns the similarity score matrix that contains similaririty score for one to all in the list
- Assistant
- User
similarity = torch.nn.functional.cosine_similarity(embedding1, embedding2.unsqueeze(0) if embedding2.ndimension()==1 else embedding2) what does this does
- Assistant
- User
print(similarity_score_matrix(embeddings)) print this in graphical form
- Assistant
- User
use os to print all files in embeddings directory without extensions
- Assistant
- User
use only os and very short code
- Assistant
Sure! Here's a short script using only the
osmodule to list and print the names of all files in a directory without their extensions:import os # Function to list files without extensions def list_files_without_extensions(directory): for file in os.listdir(directory): if os.path.isfile(os.path.join(directory, file)): print(os.path.splitext(file)[0]) # Example usage directory_path = 'embeddings' # Replace with your directory path list_files_without_extensions(directory_path)Explanation:
os.listdir(directory): Lists all entries in the specified directory, including files and subdirectories.os.path.isfile(os.path.join(directory, file)): Checks if the entry is a file (not a directory).os.path.splitext(file)[0]: Splits the filename into its name and extension, returning the name without the extension.
This short script filters the files in the given directory and prints their names without the extensions.
- User
if embeddings is None or embeddings.size(0) == 0: print("No faces detected in the input image.") else: records = mark_attendance(embeddings, directory="embeddings") shorten code
- Assistant
You can shorten the given code using a ternary conditional operator to handle the logic in a more compact form. Here's how you can do it:
records = [] if embeddings is None or embeddings.size(0) == 0 else mark_attendance(embeddings, directory="embeddings") print("No faces detected in the input image.") if not records else NoneExplanation:
-
Ternary Conditional Operator:
records = [] if embeddings is None or embeddings.size(0) == 0 else mark_attendance(embeddings, directory="embeddings")- This line assigns an empty list
[]torecordsifembeddingsisNoneor its size is0. Otherwise, it callsmark_attendance.
-
Inline Conditional Print:
print("No faces detected in the input image.") if not records else None- This line prints the message only if
recordsis empty (meaning no faces were detected).
-
- User
attendance_records.append((f'roll no: ', most_similar_filename, max_similarity)) in this also append current datetime
- Assistant
- User
print(records) convert this records to pandas dataframe
- Assistant