ydin0771 commited on
Commit
7951498
β€’
1 Parent(s): dfb84d2

Upload extract_feature.py

Browse files
Files changed (1) hide show
  1. extract_feature.py +51 -0
extract_feature.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse, os, json
2
+ import numpy as np
3
+ from imageio import imread
4
+ from PIL import Image
5
+
6
+ import torch
7
+ import torchvision
8
+ import ssl
9
+ ssl._create_default_https_context = ssl._create_unverified_context
10
+
11
+
12
+ def build_model(model='resnet101', model_stage=3):
13
+ cnn = getattr(torchvision.models, model)(pretrained=True)
14
+ layers = [
15
+ cnn.conv1,
16
+ cnn.bn1,
17
+ cnn.relu,
18
+ cnn.maxpool,
19
+ ]
20
+ for i in range(model_stage):
21
+ name = 'layer%d' % (i + 1)
22
+ layers.append(getattr(cnn, name))
23
+ model = torch.nn.Sequential(*layers)
24
+ # model.cuda()
25
+ model.eval()
26
+ return model
27
+
28
+
29
+ def run_image(img, model):
30
+ mean = np.array([0.485, 0.456, 0.406]).reshape(1, 3, 1, 1)
31
+ std = np.array([0.229, 0.224, 0.224]).reshape(1, 3, 1, 1)
32
+
33
+ image = np.concatenate([img], 0).astype(np.float32)
34
+ image = (image / 255.0 - mean) / std
35
+ image = torch.FloatTensor(image)
36
+ image = torch.autograd.Variable(image, volatile=True)
37
+
38
+ feats = model(image)
39
+ feats = feats.data.cpu().clone().numpy()
40
+
41
+ return feats
42
+
43
+
44
+ def get_img_feat(cnn_model, img, image_height=224, image_width=224):
45
+ img_size = (image_height, image_width)
46
+ img = np.array(Image.fromarray(np.uint8(img)).resize(img_size))
47
+ img = img.transpose(2, 0, 1)[None]
48
+ feats = run_image(img, cnn_model)
49
+ _, C, H, W = feats.shape
50
+ feat_dset = feats.reshape(1, C, H, W)
51
+ return feat_dset