import cv2
import numpy as np
# --- НАСТРОЙКИ ---
MODEL_FILE = "chess_pieces.onnx"
IMAGE_FILE = "board.png"
TARGET_SIZE = (256, 256) # Точный размер, который подошел твоей нейросети
# Карта классов (0 = пустая клетка '.', 1..6 = белые, 7..12 = черные)
CLASSES = ['.', 'P', 'N', 'B', 'R', 'Q', 'K', 'p', 'n', 'b', 'r', 'q', 'k']
def crop_board(image_path):
"""Вырезает и выравнивает доску под 400x400"""
img = cv2.imread(image_path)
if img is None:
raise FileNotFoundError(f"Не найден файл: {image_path}")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blur, 50, 150)
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
board_cnt = None
max_area = 0
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 10000:
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
if len(approx) == 4 and area > max_area:
board_cnt = approx
max_area = area
if board_cnt is not None:
pts = board_cnt.reshape(4, 2)
# Сортировка углов (верх-лево, верх-право, низ-право, низ-лево)
rect = np.zeros((4, 2), dtype="float32")
s = pts.sum(axis=1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
diff = np.diff(pts, axis=1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]
dst = np.array([[0, 0], [399, 0], [399, 399], [0, 399]], dtype="float32")
M = cv2.getPerspectiveTransform(rect, dst)
return cv2.warpPerspective(img, M, (400, 400))
else:
return cv2.resize(img, (400, 400))
def scan_chess():
# 1. Загрузка модели через OpenCV DNN
net = cv2.dnn.readNetFromONNX(MODEL_FILE)
# 2. Подготовка вырезанной доски
board = crop_board(IMAGE_FILE)
# 3. Нарезка 64 клеток
cells = []
cell_size = 50
for row in range(8):
for col in range(8):
y1, y2 = row * cell_size, (row + 1) * cell_size
x1, x2 = col * cell_size, (col + 1) * cell_size
cell = board[y1:y2, x1:x2]
cells.append(cell)
# 4. Формирование входного пакета 256x256
blob = cv2.dnn.blobFromImages(
cells,
scalefactor=1.0/255.0,
size=TARGET_SIZE,
swapRB=True,
crop=False
)
net.setInput(blob)
outputs = net.forward()
# 5. Определение фигур
predictions = np.argmax(outputs, axis=1)
# 6. Генерация FEN-строки
fen_rows = []
for r in range(8):
row_pieces = [CLASSES[idx] for idx in predictions[r*8:(r+1)*8]]
empty_count = 0
row_str = ""
for piece in row_pieces:
if piece == '.':
empty_count += 1
else:
if empty_count > 0:
row_str += str(empty_count)
empty_count = 0
row_str += piece
if empty_count > 0:
row_str += str(empty_count)
fen_rows.append(row_str)
final_fen = "/".join(fen_rows) + " w - - 0 1"
print("===========================================")
print("ГОТОВО! FEN позиции:")
print(final_fen)
print("===========================================")
if __name__ == "__main__":
scan_chess()