-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathget_clip_features.py
More file actions
51 lines (45 loc) · 1.71 KB
/
get_clip_features.py
File metadata and controls
51 lines (45 loc) · 1.71 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import argparse
import clip
from util.datasets_clip import build_dataset_clip
import torch
import numpy as np
BATCH_SIZE = 20
#
def get_args_parser():
parser = argparse.ArgumentParser('extract clip features', add_help=False)
parser.add_argument('--input_size', default=224, type=int,
help='images input size')
parser.add_argument('--data_path', default='E://data//carton_subset//val', type=str,
help='dataset path')
return parser
def main(args):
dataset_test = build_dataset_clip(args=args)
sampler_test = torch.utils.data.SequentialSampler(dataset_test)
data_loader_test = torch.utils.data.DataLoader(
dataset_test, sampler=sampler_test,
batch_size=BATCH_SIZE,
num_workers=2,
pin_memory=True,
drop_last=False
)
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/16", download_root='./models', device=device)
all_features = None
all_path = []
with torch.no_grad():
for samples, targets, path in data_loader_test:
samples = samples.to(device, non_blocking=True)
image_features = model.encode_image(samples)
image_features = image_features.detach().cpu().numpy()
if all_features is None:
all_features = image_features
else:
all_features = np.concatenate([all_features, image_features], axis=0)
all_path += path
if all_features.shape[0] % 100 ==0:
print(all_features.shape[0])
np.save('clip_features_subset.npy', all_features)
if __name__=='__main__':
args = get_args_parser()
args = args.parse_args()
main(args)