Loads each image in `folder`, encodes it with the CLIP model, and returns a list (or array) of embeddings, shape (N, D).
(folder, model, processor, device)
| 238 | |
| 239 | |
| 240 | def compute_clip_embeddings(folder, model, processor, device): |
| 241 | """ |
| 242 | Loads each image in `folder`, encodes it with the CLIP model, |
| 243 | and returns a list (or array) of embeddings, shape (N, D). |
| 244 | """ |
| 245 | model.eval() |
| 246 | embeddings = [] |
| 247 | |
| 248 | # Gather all image files |
| 249 | image_files = [ |
| 250 | f for f in os.listdir(folder) |
| 251 | if f.lower().endswith(('.png', '.jpg', '.jpeg')) |
| 252 | ] |
| 253 | |
| 254 | if not image_files: |
| 255 | print(f"No valid images found in {folder}") |
| 256 | return np.array([]) |
| 257 | |
| 258 | for filename in image_files: |
| 259 | img_path = os.path.join(folder, filename) |
| 260 | image = Image.open(img_path).convert('RGB') |
| 261 | |
| 262 | # Preprocess for CLIP |
| 263 | inputs = processor(images=image, return_tensors="pt").to(device) |
| 264 | |
| 265 | # Encode and get the image embeddings |
| 266 | with torch.no_grad(): |
| 267 | clip_emb = model.get_image_features(**inputs) |
| 268 | # Move to CPU and convert to NumPy |
| 269 | clip_emb = clip_emb[0].cpu().numpy() |
| 270 | embeddings.append(clip_emb) |
| 271 | |
| 272 | return np.array(embeddings) # shape: (N, D) |
| 273 | |
| 274 | def compute_clip_embedding(input_data, model, processor, device='cuda', input_type=None): |
| 275 | """ |
no test coverage detected