-
Notifications
You must be signed in to change notification settings - Fork 2
/
QuerySearch.py
57 lines (39 loc) · 1.78 KB
/
QuerySearch.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
import math
class QuerySearch:
""" Searches similarity of query image vector with extracted vectors from database"""
def __init__(self, queryFeature, features):
self.features = features
self.queryFeature = queryFeature
def __cosine_similarity(self, queryVector, vector):
# Computes cosine similarity between two vectors
eps = 1e-10
dot_product = sum(q*v for q, v in zip(queryVector, vector))
queryMagnitude = math.sqrt(sum([val**2 for val in queryVector]))
vectorMagnitude = math.sqrt(sum([val**2 for val in vector]))
magnitude = (queryMagnitude*vectorMagnitude)+eps
if not magnitude:
return 0
cosine_similarity = round(dot_product/magnitude, 5)
return cosine_similarity
def __chi2_distance(self, queryVector, vector):
# Computes chi-square distance between two vectors
eps = 1e-10
dists = [((q - v) ** 2) / (q + v + eps)
for (q, v) in zip(queryVector, vector)]
chi2_distance = 0.5 * sum(dists)
chi2_distance = round(chi2_distance, 5)
return chi2_distance
def __SAD_distance(self, queryVector, vector):
# Computes SAD distance between two vectors
dists = [abs(q-v) for (q, v) in zip(queryVector, vector)]
SAD_distance = sum(dists)
return SAD_distance
def performSearch(self):
# Return similarity indices of queryVector and databse images
searchSimilarityScores = []
for image in self.features:
queryVector = self.queryFeature
vector = self.features[image]
cosine_similarity = self.__chi2_distance(queryVector, vector)
searchSimilarityScores.append((image, cosine_similarity))
return searchSimilarityScores