import cv2
import numpy as np
MODEL_FILE = "chess_pieces.onnx"
IMAGE_FILE = "board.png"
CLASSES = ['.', 'P', 'N', 'B', 'R', 'Q', 'K', 'p', 'n', 'b', 'r', 'q', 'k']
# Размер входа модели (обычно 32x32 или 64x64).
# Если выдаст ошибку форматов — измените на (64, 64)
TARGET_SIZE = (32, 32)
def crop_board(image_path):
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():
print("Загрузка ONNX модели через OpenCV DNN (совместимо с Win 7)...")
# OpenCV считывает файл .onnx без сторонних библиотек
net = cv2.dnn.readNetFromONNX(MODEL_FILE)
print("✓ Модель успешно загружена!")
# Вырезаем доску
board = crop_board(IMAGE_FILE)
# Нарезаем 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)
# Готовим пакет из 64 картинок для нейросети
# blobFromImages сам изменит размер под TARGET_SIZE и переведет цвета
blob = cv2.dnn.blobFromImages(
cells,
scalefactor=1.0/255.0,
size=TARGET_SIZE,
swapRB=True,
crop=False
)
net.setInput(blob)
outputs = net.forward() # Прогоняем все 64 клетки за раз
predictions = np.argmax(outputs, axis=1)
# Собираем 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("\n--- УСПЕХ! ---")
print("Распознанный FEN:", final_fen)
if __name__ == "__main__":
try:
scan_chess()
except Exception as e:
print("Ошибка:", e)