-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfitness_functions.py
96 lines (68 loc) · 2.42 KB
/
fitness_functions.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
import numpy as np
def simple_matching_coefficient(image1, image2) -> float:
"""
Simple matching coefficient metric.
Args:
image1 (np.ndarray): Binary black and white image.
image2 (np.ndarray): Binary black and white image.
Returns:
float: The amount of pixels that are the same in both images divided by the total amount of pixels.
"""
assert image1.shape == image2.shape
return np.count_nonzero(image1 == image2) / image1.size
def dice_similarity(image1, image2) -> float:
"""
Dice similarity metric.
Args:
image1 (np.ndarray): Binary black and white image.
image2 (np.ndarray): Binary black and white image.
Returns:
float: Dice similarity metric.
"""
assert image1.shape == image2.shape
a, b, c = get_a_b_c(image1, image2)
return 2 * c / (a + b)
def cosine_similarity(image1, image2) -> float:
"""
Cross-correlation similarity metric.
Args:
image1 (np.ndarray): Binary black and white image.
image2 (np.ndarray): Binary black and white image.
Returns:
float: Cross-correlation similarity metric.
"""
assert image1.shape == image2.shape
a, b, c = get_a_b_c(image1, image2)
return c / np.sqrt(a * b)
def get_a_b_c(image, target_image) -> tuple[int, int, int]:
"""
Get the a, b, c values for the matching coefficient metrics based on the important color.
Args:
image (np.ndarray): Binary black and white image.
target_image (np.ndarray): Binary black and white image.
Returns:
tuple[int, int, int]: a, b, c values.
"""
assert image.shape == target_image.shape
important_pixel = get_important_color(target_image)[0]
a = np.count_nonzero(image == important_pixel)
b = np.count_nonzero(target_image == important_pixel)
c = np.count_nonzero(
np.logical_and(image == important_pixel, target_image == important_pixel)
)
return a, b, c
def get_important_color(image) -> tuple[int, int]:
"""
Get the majority color of a binary black and white image.
Args:
image (np.ndarray): Binary black and white image.
Returns:
tuple[int, int]: Minority color and its count.
"""
white = 255
black = 0
white_count = np.sum(image == white)
black_count = np.sum(image == black)
if white_count > black_count:
return black, black_count
return white, white_count