Загрузка данных


import os
import cv2
import numpy as np

# --- 1. ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ---

def extract_dominant_piece_color(cell_bgr):
    """Извлечение 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)]
    return np.mean(center, axis=(0, 1)).astype(float).tolist()


def get_piece_mask(gray_crop):
    """
    Создает четкий бинарный силуэт (маску) фигуры, 
    убирая фон клетки.
    """
    # Нормализуем контрастность
    norm = cv2.equalizeHist(gray_crop)
    # Выделяем темные/светлые объекты через адаптивный порог
    _, mask = cv2.threshold(norm, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    return mask


def print_board(board_matrix, fen):
    divider = "  +" + "---+" * 8
    print("\n    a   b   c   d   e   f   g   h")
    print(divider)
    for idx, row in enumerate(board_matrix):
        rank = 8 - idx
        row_str = " | ".join([f"{p}" if p != '.' else " " for p in row])
        print(f"{rank} | {row_str} | {rank}")
        print(divider)
    print("    a   b   c   d   e   f   g   h")
    print(f"\nFEN: {fen}\n")


def scan_frame(cell_board, color_database, templates_gray, templates_masks, ALL_PIECES, variance_threshold=14.0):
    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)
            center_gray = gray_cell[7:43, 7:43]

            # 1. Проверка на пустую клетку по дисперсии
            if np.std(center_gray) < variance_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

            # Получаем бинарную маску текущей клетки (для черных фигур)
            cell_mask = get_piece_mask(center_gray) if not is_white_piece else None

            for piece_symbol in candidate_pieces:
                if piece_symbol not in templates_gray or piece_symbol not in color_database:
                    continue
                
                # Для белых фигур — сравнение полутонов (Grayscale)
                if is_white_piece:
                    tpl_gray = templates_gray[piece_symbol]
                    res = cv2.matchTemplate(center_gray, tpl_gray, cv2.TM_CCOEFF_NORMED)
                    _, shape_score, _, _ = cv2.minMaxLoc(res)
                # Для чёрных фигур — сравнение по бинарным маскам (Silhouettes)
                else:
                    tpl_mask = templates_masks[piece_symbol]
                    res = cv2.matchTemplate(cell_mask, tpl_mask, 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 / 200.0)
                
                if score > max_score:
                    max_score = score
                    best_match = piece_symbol
                    
            row_pieces.append(best_match)
        board_matrix.append(row_pieces)

    # Сборка 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)
        
    return board_matrix, "/".join(fen_rows) + " w - - 0 1"


# --- 2. ГЛАВНЫЙ ИСПОЛНЯЕМЫЙ БЛОК ---

def main():
    TEMPLATES_DIR = "extracted_pieces"
    BOARD_IMAGE_PATH = "board.png"
    
    ALL_PIECES = ['K', 'Q', 'R', 'B', 'N', 'P', 'k', 'q', 'r', 'b', 'n', 'p']
    
    PIECES_CONFIG = {
        "K": "white_K.png", "Q": "white_Q.png", "R": "white_R.png",
        "B": "white_B.png", "N": "white_N.png", "P": "white_P.png",
        "k": "black_k.png", "q": "black_q.png", "r": "black_r.png",
        "b": "black_b.png", "n": "black_n.png", "p": "black_p.png"
    }

    if not os.path.exists(TEMPLATES_DIR):
        print(f"[ОШИБКА] Папка '{TEMPLATES_DIR}' не найдена!")
        return

    templates_gray = {}
    templates_masks = {}
    color_database = {}

    for sym, filename in PIECES_CONFIG.items():
        path = os.path.join(TEMPLATES_DIR, filename)
        if not os.path.exists(path):
            continue

        img = cv2.imread(path)
        if img is None:
            continue

        img_50 = cv2.resize(img, (50, 50))
        gray = cv2.cvtColor(img_50, cv2.COLOR_BGR2GRAY)
        crop_gray = gray[7:43, 7:43]
        
        templates_gray[sym] = crop_gray
        templates_masks[sym] = get_piece_mask(crop_gray)
        color_database[sym] = extract_dominant_piece_color(img_50)

    if not os.path.exists(BOARD_IMAGE_PATH):
        print(f"[ОШИБКА] Файл '{BOARD_IMAGE_PATH}' не найден!")
        return

    board_img = cv2.imread(BOARD_IMAGE_PATH)
    if board_img is None:
        print("[ОШИБКА] Не удалось прочитать файл изображения!")
        return

    matrix, fen = scan_frame(board_img, color_database, templates_gray, templates_masks, ALL_PIECES)
    print_board(matrix, fen)


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"\n[КРИТИЧЕСКАЯ ОШИБКА]: {e}")
        import traceback
        traceback.print_exc()
        
    input("\nНажмите Enter, чтобы закрыть окно...")