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


import cv2
import numpy as np
import os
# Импортируем модуль захвата
import crop 


class ChessAnalyzer:
    def __init__(self, templates_dir='templates', win_size=(64, 64)):
        self.templates_dir = templates_dir
        self.win_size = win_size
        
        # Настройка HOG-детектора
        self.hog = cv2.HOGDescriptor(
            _winSize=self.win_size,
            _blockSize=(16, 16),
            _blockStride=(8, 8),
            _cellSize=(8, 8),
            _nbins=9
        )
        
        # Символы фигур по стандарту FEN (Заглавные — белые, строчные — черные)
        self.piece_symbols = {
            'white_pawn': 'P', 'white_knight': 'N', 'white_bishop': 'B',
            'white_rook': 'R', 'white_queen': 'Q', 'white_king': 'K',
            'black_pawn': 'p', 'black_knight': 'n', 'black_bishop': 'b',
            'black_rook': 'r', 'black_queen': 'q', 'black_king': 'k'
        }
        
        self.templates = {}
        self.load_templates()

    def load_templates(self):
        """Загрузка PNG-шаблонов из папки templates"""
        if not os.path.exists(self.templates_dir):
            print(f"[!] Ошибка: Папка '{self.templates_dir}' не найдена.")
            return

        for filename in os.listdir(self.templates_dir):
            if filename.lower().endswith('.png'):
                piece_name = os.path.splitext(filename)[0]
                path = os.path.join(self.templates_dir, filename)
                
                img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
                if img is None:
                    continue

                img_resized = cv2.resize(img, self.win_size)

                # Обработка альфа-канала с наложением на нейтральный фон
                if img_resized.shape[2] == 4:
                    alpha = img_resized[:, :, 3] / 255.0
                    gray_piece = cv2.cvtColor(img_resized[:, :, :3], cv2.COLOR_BGR2GRAY)
                    bg = np.ones_like(gray_piece, dtype=np.uint8) * 128
                    composite_gray = (gray_piece * alpha + bg * (1 - alpha)).astype(np.uint8)
                else:
                    composite_gray = cv2.cvtColor(img_resized, cv2.COLOR_BGR2GRAY)

                hog_feat = self.hog.compute(composite_gray)
                self.templates[piece_name] = hog_feat

    def is_empty_cell(self, cell_img, stddev_threshold=18.0):
        """Проверка клетки на пустоту по стандартному отклонению яркости"""
        gray = cv2.cvtColor(cell_img, cv2.COLOR_BGR2GRAY) if len(cell_img.shape) == 3 else cell_img
        h, w = gray.shape
        inner_crop = gray[int(h*0.15):int(h*0.85), int(w*0.15):int(w*0.85)]
        
        _, stddev = cv2.meanStdDev(inner_crop)
        return stddev[0][0] < stddev_threshold

    def get_piece_color(self, cell_img):
        """Определение цвета фигуры в центре клетки (белый / черный)"""
        gray = cv2.cvtColor(cell_img, cv2.COLOR_BGR2GRAY) if len(cell_img.shape) == 3 else cell_img
        h, w = gray.shape
        center_crop = gray[int(h*0.25):int(h*0.75), int(w*0.25):int(w*0.75)]
        return 'white' if np.mean(center_crop) > 128 else 'black'

    def identify_piece(self, cell_img):
        """Распознавание фигуры на одной клетке через HOG"""
        if cell_img is None or cell_img.size == 0 or not self.templates:
            return ""

        # 1. Проверка на пустую клетку
        if self.is_empty_cell(cell_img):
            return ""

        # 2. Определение цвета фигуры
        detected_color = self.get_piece_color(cell_img)
        
        # 3. Сравнение HOG-признаков
        cell_resized = cv2.resize(cell_img, self.win_size)
        gray = cv2.cvtColor(cell_resized, cv2.COLOR_BGR2GRAY) if len(cell_resized.shape) == 3 else cell_resized
        cell_hog = self.hog.compute(gray)
        
        best_piece = ""
        min_dist = float('inf')

        for piece_name, template_hog in self.templates.items():
            # Отсекаем фигуры чужого цвета
            if not piece_name.startswith(detected_color):
                continue

            dist = np.linalg.norm(cell_hog - template_hog)
            if dist < min_dist:
                min_dist = dist
                best_piece = piece_name

        if min_dist < 15.0 and best_piece:
            return self.piece_symbols.get(best_piece, "")
        
        return ""

    def analyze_initial_board(self):
        """
        ЕДИНОРАЗОВЫЙ ВЫЗОВ:
        Запрашивает снимок доски у crop.py через функцию find_chessboard_strictly_1to1(),
        нарезает его и отдаёт матрицу 8x8 с FEN-символами.
        """
        # Вызываем функцию из crop.py
        board_matrix_crop, board_img = crop.find_chessboard_strictly_1to1()
        
        if board_img is None:
            print("[!] Не удалось найти шахматную доску на экране через crop.py!")
            return []

        h, w = board_img.shape[:2]
        cell_h = h // 8
        cell_w = w // 8

        board_matrix = []

        # Нарезаем доску на 64 клетки и распознаем каждую
        for row in range(8):
            row_pieces = []
            for col in range(8):
                y1, y2 = row * cell_h, (row + 1) * cell_h
                x1, x2 = col * cell_w, (col + 1) * cell_w
                cell_crop = board_img[y1:y2, x1:x2]

                symbol = self.identify_piece(cell_crop)
                row_pieces.append(symbol)
            
            board_matrix.append(row_pieces)

        return board_matrix