-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimilarity_methods.py
80 lines (63 loc) · 2.45 KB
/
similarity_methods.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
import cv2
import numpy as np
from tqdm import tqdm
def histogramSimilarityMatrix(
listImage1: list, listImage2: list, compare_method=cv2.HISTCMP_INTERSECT, **kwargs
) -> np.ndarray:
"""
Calculate the histogram similarity between each image
"""
S = np.zeros((len(listImage1), len(listImage2)))
progress_bar = tqdm(
total=len(listImage1), ncols=100, desc="Creating similarity matrix"
)
list_histo_1 = [
cv2.calcHist(img1, [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])
for img1 in listImage1
]
list_histo_2 = [
cv2.calcHist(img2, [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])
for img2 in listImage2
]
for i, hist1 in enumerate(list_histo_1):
progress_bar.update(1)
for j, hist2 in enumerate(list_histo_2):
S[i, j] = cv2.compareHist(hist1, hist2, compare_method)
progress_bar.close()
return S * -1
def colorSimilarityMatrix(listImage1: list, listImage2: list, **kwargs) -> np.ndarray:
"""
Calculate the euclidean distance between each image
"""
# Convert all images to int16 to avoid overflow
listImage1 = [img.astype(np.int16) for img in listImage1]
listImage2 = [img.astype(np.int16) for img in listImage2]
S = np.zeros((len(listImage1), len(listImage2)))
progress_bar = tqdm(
total=len(listImage1), ncols=100, desc="Creating similarity matrix"
)
for i, img1 in enumerate(listImage1):
progress_bar.update(1)
# Vectorized computation of distances
differences = np.array(listImage2) - img1
distances = np.linalg.norm(differences.reshape(len(listImage2), -1), axis=1)
S[i, :] = distances
progress_bar.close()
return S
def averageColorMatrix(listImage1: list, listImage2: list, **kwargs) -> np.ndarray:
"""
Calculate the average color of each image and then calculate the euclidean distance between them
"""
S = np.zeros((len(listImage1), len(listImage2)))
progress_bar = tqdm(
total=len(listImage1), ncols=100, desc="Creating similarity matrix"
)
for i, img1 in enumerate(listImage1):
progress_bar.update(1)
for j, img2 in enumerate(listImage2):
# change dtype to int16 to avoid overflow
img1 = img1.astype(np.int16)
img2 = img2.astype(np.int16)
S[i, j] = np.linalg.norm(np.mean(img1, axis=2) - np.mean(img2, axis=2))
progress_bar.close()
return S