-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
71 lines (64 loc) · 1.88 KB
/
utils.py
File metadata and controls
71 lines (64 loc) · 1.88 KB
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
import chess
import chess.svg
from io_utils import svg_to_image
import cv2
import numpy as np
class EmptySquare:
def __init__(self):
pass
def symbol(self):
return 'empty'
def __eq__(self, other):
return isinstance(other, EmptySquare)
def board_to_matrix(board):
"""
Given a chess.Board object, returns a matrix representation of the board
Piece are classified as follows:
[K, Q, R, B, N, P] for white pieces
[k, q, r, b, n, p] for black pieces
EmptySquare for empty squares
"""
matrix = [[EmptySquare() for _ in range(8)] for _ in range(8)]
for i in range(8)[::-1]: # chess.Board mapping is reversed, with white at the bottom
for j in range(8):
piece = board.piece_at(i * 8 + j)
if piece is not None:
matrix[i][j] = piece.symbol()
return matrix
def image_from_fen(fen):
"""
Given a FEN string, returns a PIL image of the board
"""
board = chess.Board(fen)
svg = chess.svg.board(board=board)
return svg_to_image(svg)
def PIL2cv2(PIL_img):
"""
Convert a PIL image to a cv2 image
"""
return cv2.cvtColor(np.array(PIL_img), cv2.COLOR_RGB2BGR)
def matrix_to_fen(board):
"""
Given a matrix representation of a chess board, returns the FEN string
Piece are classified as follows:
[K, Q, R, B, N, P] for white pieces
[k, q, r, b, n, p] for black pieces
EmptySquare for empty squares
"""
fen = ''
for i in range(8)[::-1]:
empty = 0
for j in range(8):
piece = board[i][j]
if isinstance(piece, EmptySquare):
empty += 1
else:
if empty > 0:
fen += str(empty)
empty = 0
fen += piece
if empty > 0:
fen += str(empty)
if i > 0:
fen += '/'
return fen