基于遗传算法的自动拼图(一)

参考自github项目 https://github.com/nemanja-m/gaps

加了注释及自己的理解

先选择一张图片 男神镇楼

把一张图片变成拼图

1
2
3
4
5
6
7
8
9
10
11
12
def create_puzzle(image_path, output_path, piece_size):
image = cv2.imread(image_path)
pieces, rows, columns = image_helpers.flatten_image(image, piece_size)

# Randomize pieces in order to make puzzle
np.random.shuffle(pieces)

# Create puzzle by stacking pieces
puzzle = image_helpers.assemble_image(pieces, rows, columns)
# 把拼图写入指定路径
cv2.imwrite(output_path, puzzle)
print_messages(["Puzzle created with {} pieces".format(len(pieces))])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def flatten_image(image, piece_size, indexed=False):
#//是整除符号
#每块碎片大小都一样 所给图片能整除这块碎片的宽和高
rows, columns = image.shape[0] // piece_size, image.shape[1] // piece_size
pieces = []

# Crop pieces from original image
for y in range(rows):
for x in range(columns):
left, top, w, h = x * piece_size, y * piece_size, (x + 1) * piece_size, (y + 1) * piece_size
piece = np.empty((piece_size, piece_size, image.shape[2]))
piece[:piece_size, :piece_size, :] = image[top:h, left:w, :]
pieces.append(piece)

if indexed:
pieces = [Piece(value, index) for index, value in enumerate(pieces)]

return pieces, rows, columns
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 class Piece(object):
"""
Usage::

>>> from gaps.piece import Piece
>>> piece = Piece(image[:28, :28, :], 42)
"""
def __init__(self, image, index):
self.image = image[:]
self.id = index

def __getitem__(self, index):
return self.image.__getitem__(index)

def size(self):
"""Returns piece size"""
return self.image.shape[0]

def shape(self):
"""Returns shape of piece's image"""
return self.image.shape
1
2
3
4
5
6
7
8
9
10
def assemble_image(pieces, rows, columns):
##竖直的栈
vertical_stack = []
for i in range(rows):
##水平的栈
horizontal_stack = []
for j in range(columns):
horizontal_stack.append(pieces[i * columns + j])
vertical_stack.append(np.hstack(horizontal_stack))
return np.vstack(vertical_stack).astype(np.uint8)

参考链接

关于 hstack和vstack函数
https://blog.csdn.net/garfielder007/article/details/51378296

https://blog.csdn.net/csdn15698845876/article/details/73380803