-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.py
183 lines (151 loc) · 5.19 KB
/
helpers.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import psutil
import os
import shutil
from shutil import *
import numpy as np
import torch
from PIL import Image
import glob
class HelperFunctions(object):
def __init__(self):
# Some Helper functions
# self.id_map = self.load_imagenet_id_map()
# self.label_map = self.load_imagenet_label_map()
# self.key_list = list(self.id_map.keys())
# self.val_list = list(self.id_map.values())
pass
def concat(self, x):
return np.concatenate(x, axis=0)
def to_np(self, x):
return x.data.to("cpu").numpy()
def to_ts(self, x):
return torch.from_numpy(x)
def train_extract_wnid(self, x):
return x.split("train/")[1].split("/")[0]
def val_extract_wnid(self, x):
# return x.split(x + '/')[1].split('/')[0]
return x.split("/")[-2]
def rm_and_mkdir(self, path):
if os.path.isdir(path) == True:
rmtree(path)
os.mkdir(path)
def copy_files(self, files, dir):
for file in files:
shutil.copy(file, dir)
def is_grey_scale(self, img_path):
img = Image.open(img_path).convert("RGB")
w, h = img.size
for i in range(w):
for j in range(h):
r, g, b = img.getpixel((i, j))
if r != g != b:
return False
return True
def check_and_mkdir(self, f):
if not os.path.exists(f):
os.mkdir(f)
else:
pass
def check_and_rm(self, f):
if os.path.exists(f):
shutil.rmtree(f)
else:
pass
def load_imagenet_label_map(self):
"""
Load ImageNet label dictionary.
return:
"""
input_f = open(f"{RunningParams.parent_dir}/kNN-classifiers/input_txt_files/imagenet_classes.txt")
label_map = {}
for line in input_f:
parts = line.strip().split(": ")
(num, label) = (int(parts[0]), parts[1].replace('"', ""))
label_map[num] = label
input_f.close()
return label_map
# Added for loading ImageNet classes
def load_imagenet_id_map(self):
"""
Load ImageNet ID dictionary.
return;
"""
input_f = open(f"{RunningParams.parent_dir}/KNN-ImageNet/synset_words.txt")
label_map = {}
for line in input_f:
parts = line.strip().split(" ")
(num, label) = (parts[0], " ".join(parts[1:]))
label_map[num] = label
input_f.close()
return label_map
def convert_imagenet_label_to_id(
self, label_map, key_list, val_list, prediction_class
):
"""
Convert imagenet label to ID: for example - 245 -> "French bulldog" -> n02108915
:param label_map:
:param key_list:
:param val_list:
:param prediction_class:
:return:
"""
class_to_label = label_map[prediction_class]
prediction_id = key_list[val_list.index(class_to_label)]
return prediction_id
def convert_imagenet_id_to_label(self, key_list, class_id):
"""
Convert imagenet label to ID: for example - n02108915 -> "French bulldog" -> 245
:param label_map:
:param key_list:
:param val_list:
:param prediction_class:
:return:
"""
return key_list.index(str(class_id))
def load_imagenet_validation_gt(self):
count = 0
input_f = open(f"{RunningParams.parent_dir}/kNN-classifiers/input_txt_files/ILSVRC2012_validation_ground_truth.txt")
gt_dict = {}
while True:
count += 1
# Get the next line
line = input_f.readline()
# if line is empty, EOL is reached
if not line:
break
gt_dict[count] = int(line.strip())
input_f.close()
return gt_dict
def load_imagenet_dog_label(self):
dog_id_list = list()
input_f = open(f"{RunningParams.parent_dir}/ImageNet_Dogs_dataset/dog_type.txt")
for line in input_f:
dog_id = (line.split('-')[0])
dog_id_list.append(dog_id)
return dog_id_list
@staticmethod
def is_program_running(script):
"""
Check if a script is already running
:param script:
:return:
"""
for q in psutil.process_iter():
if q.name().startswith('python'):
if len(q.cmdline())>1 and script in q.cmdline()[1] and q.pid !=os.getpid():
print("'{}' Process is already running".format(script))
return True
return False
@staticmethod
def count_two_lists_overlap(a, b):
return len(set(a) & set(b))
@staticmethod
def count_overlaps_by_two_paths(path1, path2):
samples = {path1: [], path2: []}
for path in [path1, path2]:
image_folders = glob.glob('{}/*'.format(path))
for i, image_folder in enumerate(image_folders):
image_paths = glob.glob(image_folder + '/*.*')
for image in image_paths:
samples[path].append(os.path.basename(image))
return HelperFunctions.count_two_lists_overlap(samples[path1], samples[path2])