-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelperCLIP.py
More file actions
327 lines (245 loc) · 9.67 KB
/
HelperCLIP.py
File metadata and controls
327 lines (245 loc) · 9.67 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
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import torch
from torchvision import transforms
import os
from PIL import Image
import cv2
import numpy as np
import math
import clip
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
def getAllImagesFromFolder(folder):
image_files = os.listdir(folder)
image_files = [f for f in image_files if f.endswith('.png') or f.endswith('.jpg')]
return image_files
CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073]
CLIP_STD = [0.26862954, 0.26130258, 0.27577711]
CLIP_TRANSFORM = transforms.Compose([
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(CLIP_MEAN, CLIP_STD)
])
class TextVector:
def __init__(self, text, vector = None):
self.text = text
self.vector = vector
class ClipHelper:
def __init__(self, device : torch.device = None):
if device is None:
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
else:
self.device = device
print(f'Using device {self.device}')
self.model, self.preprocess = clip.load("ViT-B/32", device="cpu")
self.model = self.model.to(self.device)
self.model.eval()
def encodeImage(self, image) -> np.ndarray:
#if image is opencv image, convert to PIL
if isinstance(image, np.ndarray):
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = Image.fromarray(image)
with torch.no_grad():
image_tensor : torch.Tensor = self.preprocess(image)
image_tensor = image_tensor.unsqueeze(0)
image = image_tensor.to(self.device)
image_features : torch.Tensor = self.model.encode_image(image)[0]
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
return image_features.cpu().numpy()
def encodeText(self, text) -> np.ndarray:
with torch.no_grad():
text_tensor : torch.Tensor = clip.tokenize(text)
text_tensor = text_tensor.to(self.device)
text_features : torch.Tensor = self.model.encode_text(text_tensor)
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
return text_features.cpu().numpy()
def createTextVector(self, text : str) -> TextVector:
return TextVector(text, self.encodeText(text)[0])
# def classifyAllImagesInFolder(self, folder, max_count = -1) -> list[tuple[str, np.ndarray]]:
# image_files = getAllImagesFromFolder(folder)
# image_files = [os.path.join(folder, f) for f in image_files]
# if max_count > 0 and max_count < len(image_files):
# image_files = random.sample(image_files, max_count)
# results = []
# for i, image_file in enumerate(image_files):
# print(f'processing image {i}/{len(image_files)}')
# image = Image.open(image_file).convert('RGB')
# outputs = self.classify(image)
# results.append((image_file, outputs[0].cpu().numpy()))
# return results
class Vec2:
def __init__(self, x:float = 0.0, y:float = 0.0):
self.x = x
self.y = y
def __add__(self, other: 'Vec2'):
return Vec2(self.x + other.x, self.y + other.y)
def __sub__(self, other: 'Vec2'):
return Vec2(self.x - other.x, self.y - other.y)
def __mul__(self, other: float):
return Vec2(self.x * other, self.y * other)
def __truediv__(self, other: float):
return Vec2(self.x / other, self.y / other)
def __str__(self):
return f'({self.x}, {self.y})'
def __repr__(self):
return f'({self.x}, {self.y})'
@property
def length(self):
return math.sqrt(self.x * self.x + self.y * self.y)
def distance(self, other : 'Vec2'):
dx = self.x - other.x
dy = self.y - other.y
return math.sqrt(dx * dx + dy * dy)
def distanceSquared(self, other : 'Vec2'):
dx = self.x - other.x
dy = self.y - other.y
return dx * dx + dy * dy
def clone(self):
return Vec2(self.x, self.y)
def set(self, x, y):
self.x = x
self.y = y
def setMin(self, other : 'Vec2'):
self.x = min(self.x, other.x)
self.y = min(self.y, other.y)
def setMax(self, other : 'Vec2'):
self.x = max(self.x, other.x)
self.y = max(self.y, other.y)
def normalized(self):
copy = self.clone()
copy.normalize()
return copy
def normalize(self):
l = self.length
if l > 0:
self.x /= l
self.y /= l
def lerp(self, other : 'Vec2', t : float):
return Vec2(self.x + (other.x - self.x) * t, self.y + (other.y - self.y) * t)
def dot(self, other: 'Vec2'):
return self.x * other.x + self.y * other.y
def angle(self, other : 'Vec2'):
return np.arccos(self.dot(other) / (self.length * other.length))
def rotate(self, angle):
return Vec2(self.x * np.cos(angle) - self.y * np.sin(angle), self.x * np.sin(angle) + self.y * np.cos(angle))
def toTuple(self):
return (self.x, self.y)
def toIntTuple(self):
return (int(self.x), int(self.y))
def toIntList(self):
return [int(self.x), int(self.y)]
def toList(self):
return [self.x, self.y]
def toNumpy(self):
return np.array([self.x, self.y], dtype=np.float32)
class Bounds2:
def __init__(self, min : Vec2 = Vec2(), max : Vec2 = Vec2()):
self.min = min
self.max = max
@property
def size(self):
return self.max - self.min
@property
def width(self):
return self.max.x - self.min.x
@property
def height(self):
return self.max.y - self.min.y
@property
def center(self):
return (self.min + self.max) / 2
def contains(self, point : Vec2):
return point.x >= self.min.x and point.x <= self.max.x and point.y >= self.min.y and point.y <= self.max.y
def containsBounds(self, other : 'Bounds2'):
return self.contains(other.min) and self.contains(other.max)
def expand(self, amount : float):
self.min -= Vec2(amount, amount)
self.max += Vec2(amount, amount)
def expandVec(self, amount : Vec2):
self.min -= amount
self.max += amount
def expandToInclude(self, point : Vec2):
self.min.setMin(point)
self.max.setMax(point)
def expandToIncludeBounds(self, other : 'Bounds2'):
self.min.setMin(other.min)
self.max.setMax(other.max)
def intersects(self, other : 'Bounds2'):
return self.min.x <= other.max.x and self.max.x >= other.min.x and self.min.y <= other.max.y and self.max.y >= other.min.y
def intersection(self, other : 'Bounds2'):
result = Bounds2()
result.min.x = max(self.min.x, other.min.x)
result.min.y = max(self.min.y, other.min.y)
result.max.x = min(self.max.x, other.max.x)
result.max.y = min(self.max.y, other.max.y)
return result
def union(self, other : 'Bounds2'):
result = Bounds2()
result.min.x = min(self.min.x, other.min.x)
result.min.y = min(self.min.y, other.min.y)
result.max.x = max(self.max.x, other.max.x)
result.max.y = max(self.max.y, other.max.y)
return result
class FolderBrowser:
def __init__(self, root_folder : str, extensions : list[str] = None, folder_browser : bool = False):
self.root_folder = root_folder
self.extensions = extensions
self.folder_browser = folder_browser
self.files = []
self.folders = []
self.stack = []
self.current_folder = root_folder
self.selected : str = None
self.update()
@property
def selected_full_path(self):
if self.selected is not None:
return self.getFullPath(self.selected)
else:
return None
def home(self):
self.unselect()
self.stack = []
self.current_folder = self.root_folder
self.update()
def up(self):
self.unselect()
if len(self.stack) > 0:
self.current_folder = self.stack.pop()
self.update()
else:
self.current_folder = os.path.dirname(self.current_folder)
self.update()
def openFolder(self, folder : str):
self.stack.append(self.current_folder)
self.current_folder = self.getFullPath(folder)
self.unselect()
self.update()
def onSelcected(self, file : str):
self.selected = file
def unselect(self):
self.selected = None
def onClose(self):
self.unselect()
def update(self):
self.files = []
self.folders = []
if os.path.isdir(self.current_folder):
if self.folder_browser:
#self.folders.append('..')
for f in os.listdir(self.current_folder):
full_path = os.path.join(self.current_folder, f)
if os.path.isdir(full_path):
self.folders.append(f)
else:
for f in os.listdir(self.current_folder):
full_path = os.path.join(self.current_folder, f)
if os.path.isdir(full_path):
self.folders.append(f)
else:
if self.extensions is None or f.endswith(tuple(self.extensions)):
self.files.append(f)
else:
print(f'{self.current_folder} is not a folder')
def getFullPath(self, file : str):
return os.path.join(self.current_folder, file)