-
Notifications
You must be signed in to change notification settings - Fork 108
/
fitness.py
52 lines (39 loc) · 1.76 KB
/
fitness.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
import numpy as np
def dissimilarity_measure(first_piece, second_piece, orientation="LR"):
"""Calculates color difference over all neighboring pixels over all color channels.
The dissimilarity measure relies on the premise that adjacent jigsaw pieces
in the original image tend to share similar colors along their abutting
edges, i.e., the sum (over all neighboring pixels) of squared color
differences (over all three color bands) should be minimal. Let pieces pi ,
pj be represented in normalized L*a*b* space by corresponding W x W x 3
matrices, where W is the height/width of each piece (in pixels).
:params first_piece: First input piece for calculation.
:params second_piece: Second input piece for calculation.
:params orientation: How input pieces are oriented.
LR => 'Left - Right'
TD => 'Top - Down'
Usage::
>>> from gaps.fitness import dissimilarity_measure
>>> from gaps.piece import Piece
>>> p1, p2 = Piece(), Piece()
>>> dissimilarity_measure(p1, p2, orientation="TD")
"""
rows, columns, _ = first_piece.shape()
color_difference = None
# | L | - | R |
if orientation == "LR":
color_difference = (
first_piece[:rows, columns - 1, :] - second_piece[:rows, 0, :]
)
# | T |
# |
# | D |
if orientation == "TD":
color_difference = (
first_piece[rows - 1, :columns, :] - second_piece[0, :columns, :]
)
squared_color_difference = np.power(color_difference / 255.0, 2)
color_difference_per_row = np.sum(squared_color_difference, axis=1)
total_difference = np.sum(color_difference_per_row, axis=0)
value = np.sqrt(total_difference)
return value