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


import os
import cv2
import numpy as np

# Твоя функция сканирования
def scan_frame(cell_board, color_database, templates_edges, ALL_PIECES):
    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)
            cell_edge = cv2.Canny(gray_cell[7:43, 7:43], 50, 150)

            if np.count_nonzero(cell_edge) < 25:
                row_pieces.append('.')
                continue

            # Извлечение цвета (медиана)
            h, w, _ = cell.shape
            center = cell[int(h * 0.25):int(h * 0.75), int(w * 0.25):int(w * 0.75)]
            cell_color = np.median(center, axis=(0, 1))

            best_match, max_score = '.', -999.0

            for piece_symbol in ALL_PIECES:
                if piece_symbol not in templates_edges or piece_symbol not in color_database:
                    continue
                
                # Сравнение формы
                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 - tpl_color)
                
                score = shape_score - (color_dist / 100.0)
                
                if score > max_score:
                    max_score = score
                    best_match = piece_symbol
                    
            row_pieces.append(best_match)
        board_matrix.append(row_pieces)

    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"


# --- БЛОК ДИАГНОСТИКИ И ТЕСТИРОВАНИЯ ---
if __name__ == "__main__":
    TEMPLATES_DIR = "extracted_pieces"
    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"
    }

    print("--- ЗАПУСК ДИАГНОСТИКИ ---")

    # 1. Проверяем папку с шаблонами
    if not os.path.exists(TEMPLATES_DIR):
        print(f"[ОШИБКА] Папка '{TEMPLATES_DIR}' не найдена!")
        input("\nНажмите Enter...")
        exit()

    templates_edges = {}
    color_database = {}

    # 2. Подготовка шаблонов и базы цветов
    for sym, filename in PIECES_CONFIG.items():
        path = os.path.join(TEMPLATES_DIR, filename)
        if not os.path.exists(path):
            print(f"[ПРЕДУПРЕЖДЕНИЕ] Файл {filename} не найден в {TEMPLATES_DIR}")
            continue

        img = cv2.imread(path)
        if img is None:
            print(f"[ОШИБКА] Не удалось прочитать картинку {filename}")
            continue

        # Приводим к 50x50, чтобы вырезка [7:43, 7:43] давала строго 36x36
        img_50 = cv2.resize(img, (50, 50))
        gray = cv2.cvtColor(img_50, cv2.COLOR_BGR2GRAY)
        
        # Записываем Canny шаблона
        templates_edges[sym] = cv2.Canny(gray[7:43, 7:43], 50, 150)
        
        # Записываем цвет шаблона
        h, w, _ = img_50.shape
        center = img_50[int(h * 0.25):int(h * 0.75), int(w * 0.25):int(w * 0.75)]
        color_database[sym] = np.median(center, axis=(0, 1)).tolist()

    print(f"[ОК] Загружено шаблонов: {len(templates_edges)}/12")

    # 3. Тестовый прогон на фейковом изображении (или замени на реальную картинку доски)
    test_board = np.zeros((400, 400, 3), dtype=np.uint8) # Пустое изображение для теста

    try:
        matrix, fen = scan_frame(test_board, color_database, templates_edges, ALL_PIECES)
        print("[УСПЕХ] Тестовое сканирование прошло без ошибок!")
        print("FEN:", fen)
    except Exception as e:
        print(f"\n[ОШИБКА В SCAN_FRAME]: {e}")
        import traceback
        traceback.print_exc()

    input("\nНажмите Enter, чтобы закрыть...")