File size: 1,009 Bytes
77fd092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import clip
import os
from PIL import Image
import numpy as np
import torch

device = 'cpu'
model_path = "weights/ViT-B-32.pt"

model, preprocess = clip.load('ViT-B/32', device)


def get_emb(image_folder):
    image_folder = image_folder
    image_paths = []
    for filename in os.listdir(image_folder):
            if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png"):
                    image_path = os.path.join(image_folder, filename)
                    image_paths.append(image_path)
            paths = image_paths
    images = [Image.open(path) for path in image_paths]
    with torch.no_grad():
        features = []
        for image in images:
            image_tensor = preprocess(image).unsqueeze(0).to(device)
            feature = model.encode_image(image_tensor)
            features.append(feature.detach().cpu().numpy())
        features = np.array(features)
    np.save("emb_images.npy", features)
    return features, paths