import cv2
import numpy as np
def extract_dominant_piece_color(cell_bgr):
"""Безопасное извлечение цвета центра клетки."""
h, w = cell_bgr.shape[:2]
center = cell_bgr[int(h * 0.25):int(h * 0.75), int(w * 0.25):int(w * 0.75)]
# Используем mean вместо median для стабильности формата
mean_color = np.mean(center, axis=(0, 1))
return mean_color.astype(float).tolist()
def scan_frame(cell_board, color_database, templates_edges, ALL_PIECES, empty_threshold=12):
"""
Сканирует доску. Возвращает (board_matrix, fen_string).
"""
board = cv2.resize(cell_board, (400, 400))
board_matrix = []
for row in range(8):
row_pieces = []
for col in range(8):
cell = board[row * 50:(row + 1) * 50, col * 50:(col + 1) * 50]
gray_cell = cv2.cvtColor(cell, cv2.COLOR_BGR2GRAY)
# Canny контуры
cell_edge = cv2.Canny(gray_cell[7:43, 7:43], 30, 120)
# 1. Отсекаем пустые клетки
if np.count_nonzero(cell_edge) < empty_threshold:
row_pieces.append('.')
continue
# 2. Безопасно определяем цвет
cell_color_vec = np.array(extract_dominant_piece_color(cell))
brightness = np.mean(cell_color_vec)
# Разделение: белая или черная фигура
is_white_piece = brightness > 110
candidate_pieces = [p for p in ALL_PIECES if p.isupper() == is_white_piece]
best_match, max_score = '.', -999.0
for piece_symbol in candidate_pieces:
if piece_symbol not in templates_edges or piece_symbol not in color_database:
continue
# Сравнение формы Canny
res = cv2.matchTemplate(cell_edge, templates_edges[piece_symbol], cv2.TM_CCOEFF_NORMED)
_, shape_score, _, _ = cv2.minMaxLoc(res)
# Штраф за расхождение цвета
tpl_color = np.array(color_database[piece_symbol])
color_dist = np.linalg.norm(cell_color_vec - tpl_color)
score = shape_score - (color_dist / 120.0)
if score > max_score:
max_score = score
best_match = piece_symbol
row_pieces.append(best_match)
board_matrix.append(row_pieces)
# 3. Формирование FEN
fen_rows = []
for r in board_matrix:
empty, row_str = 0, ""
for p in r:
if p == '.':
empty += 1
else:
if empty > 0:
row_str += str(empty)
empty = 0
row_str += p
if empty > 0:
row_str += str(empty)
fen_rows.append(row_str)
fen_string = "/".join(fen_rows) + " w - - 0 1"
return board_matrix, fen_string
# --- БЕЗОПАСНЫЙ ТЕСТОВЫЙ ЗАПУСК ---
if __name__ == "__main__":
try:
# Здесь вызов твоей основной функции/скрипта
print("[ИНФО] Запуск сканирования...")
# Замени your_board_image, color_database, templates_edges, ALL_PIECES на свои переменные:
# matrix, fen = scan_frame(your_board_image, color_database, templates_edges, ALL_PIECES)
# print("FEN:", fen)
except Exception as e:
print(f"\n[КРИТИЧЕСКАЯ ОШИБКА]: {e}")
import traceback
traceback.print_exc()
input("\nНажмите Enter, чтобы закрыть окно...")