• Stars
    star
    478
  • Rank 91,950 (Top 2 %)
  • Language
    Jupyter Notebook
  • License
    MIT License
  • Created almost 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Predict chessboard FEN layouts from images using TensorFlow

TensorFlow Chessbot - /u/ChessFenBot [â—• _ â—•]* I make FENs

CLI and Bot code lives on the chessfenbot branch

Live demo here using TensorflowJs

TL;DR:

Turn http://i.imgur.com/HnWYt8A.png → 1nkr4/1p3q1p/pP4pn/P1r5/3N1p2/2b2B1P/5PPB/2RQ1RK1

Prediction

A TensorFlow Convolutional Neural Network algorithm trained on 32x32 grayscale chess tiles predicts chessboards layouts from online chessboard screenshots.

  • 5x5x32 Input Convolution layer
  • 5x5x64 Convolution layer
  • 8x8x1024 Dense Fully Connected layer
  • 1024x13 Dropout + Softmax Readout layer

Yes, using a CNN is kinda overkill, but it is exciting.

Running Tensorflow_Chessbot on images locally and via URLs

On a linux machine which has Tensorflow and SciPy installed

Download the chessfenbot branch somewhere : tensorflow_chessbot/chessfenbot

Alternatively clone the chessfenbot branch

Now, to run pass the following arguments to tensorflow_chessbot.py

$ ./tensorflow_chessbot.py -h
usage: tensorflow_chessbot.py [-h] [--url URL] [--filepath FILEPATH]

Predict a chessboard FEN from supplied local image link or URL

optional arguments:
  -h, --help           show this help message and exit
  --url URL            URL of image (ex. http://imgur.com/u4zF5Hj.png)
  --filepath FILEPATH  filepath to image (ex. u4zF5Hj.png)

By default, it will try and load the URL http://imgur.com/u4zF5Hj.png and make a prediction in it, otherwise, you could pass a local file like so (for example with an image file u4zF5Hj.png located in the same directory):

./tensorflow_chessbot.py --filepath u4zF5Hj.png

Which should output something like:

./tensorflow_chessbot.py --filepath ./u4zF5Hj.png
Setting up CNN TensorFlow graph...
I tensorflow/core/common_runtime/local_device.cc:40] Local device intra op parallelism threads: 2
I tensorflow/core/common_runtime/direct_session.cc:58] Direct session inter op parallelism threads: 2
Loading model 'saved_models/model_10000.ckpt'
Model restored.
Certainty range [0.999545 - 1], Avg: 0.999977, Overall: 0.998546
Predicted FEN: 11111111/11111p11/11111k1P/11p1111P/1p1p1111/11111111/111K1111/11111111
Certainty: 99.9%
Done

Similarly, a URL can be tested by calling with a URL:

$ ./tensorflow_chessbot.py --url http://imgur.com/u4zF5Hj.png

Reddit Bot Deprecated

Code lives on the chessfenbot branch

/u/ChessFenBot used to (~2015-2016) automatically reply to reddit /r/chess new topic image posts that contain detectable online chessboard screenshots. A screenshot either ends in .png, .jpg, .gif, or is an imgur link.

It replies with a lichess analysis link for that layout and a predicted FEN.

predictor = ChessboardPredictor()
fen, certainty = predictor.makePrediction('http://imgur.com/u4zF5Hj.png')
print "Predicted FEN: %s" % fen
print "Certainty: %.1f%%" % (certainty*100)
Certainty range [0.999545 - 1], Avg: 0.999977, Overall: 0.998546
Predicted FEN: 8/5p2/5k1P/2p4P/1p1p4/8/3K4/8
Certainty: 99.9%
Done
[Finished in 1.8s]

ChessFenBot automatically replied to this reddit post, it processed the screenshot link url and responded with:

ChessFenBot [â—• _ â—•]* I make FENs


I attempted to generate a chessboard layout from the posted image, with an overall certainty of 99.9916%.

FEN: 1nkr4/1p3q1p/pP4pn/P1r5/3N1p2/2b2B1P/5PPB/2RQ1RK1

Here is a link to a Lichess Analysis - White to play


Yes I am a machine learning bot | How I work | Reply with a corrected FEN or Editor link) to add to my next training dataset

Workflow

There are three ipython notebooks which show the workflow from turning a screenshot of a chessboard into a set of 32x32 grayscale tiles, to generating those tiles for training and testing, and then the actual training and learning of the neural network from those trials using TensorFlow.

  1. tensorflow_compvision.ipynb - Computer Vision
  2. tensorflow_generate_training_data.ipynb - Generating a dataset from set of screenshots of chessboards in known configurations
  3. tensorflow_learn.ipynb - TensorFlow Neural Network Training & Prediction Basic Regression classifier, works for more common lichess.org and chess.com screenshots
  4. tensorflow_learn_cnn.ipynb - TensorFlow Convolutional Neural Network Training & Prediction tested with ~73% success rate on 71 chess subreddit posts

tensorflow_compvision.ipynb - 1. Computer Vision

Here is a screenshot with the detected lines of the chessboard overlaid, showing where we'll cut the image into tiles.

overlay lines


tensorflow_generate_training_data.ipynb - 2. Generating a dataset

Lichess.org provides a URL interface with a FEN string that loads a webpage with that board arrayed. A nice repo called pythonwebkit2png provides a way to render webpages programmatically, allowing us to generate several (80 in thise) random FEN strings, load the URL and take a screenshot all automatically.

random fen

Here is 5 example tiles and their associated label, a 13 length one-hot vector corresponding to 6 white pieces, 6 black pieces, and 1 empty space.

dataset example


tensorflow_learn.ipynb - 3. TensorFlow Neural Network Training & Prediction

We train the neural network on generated data from 80 lichess.org screenshots, which is 5120 tiles. We test it with 5 screenshots (320 tiles) as a quick sanity check. Here is a visualization of the weights for the white King, Queen and Rook.

Some weights

Finally we can make predictions on images passed by URL, the ones from lichess and visually similar boards work well, the ones that are too different from what we trained for don't work, suggesting that getting more data is in order. Here is a prediction on the image for this reddit post

Prediction


tensorflow_learn_cnn.ipynb - TensorFlow Convolutional Neural Network Training & Prediction

Built a slightly larger dataset of ~150 screenshots which is around 9600 tiles which includes randomized FEN diagrams from lichess.org, chess.com, and 2 FEN generated diagram sites.

Tested with ~73% success rate on 71 chess subreddit posts, good enough to make a first draft Reddit bot.


Ideation

Reddit post has an image link (perhaps as well as a statement "white/black to play").

Bot takes the image, uses some CV to find a chessboard on it, splits up into a set of images of squares. These are the inputs to the tensorflow CNN which will return probability of which piece is on it (or empty)

Dataset will include chessboard squares from chess.com, lichess Different styles of each, all the pieces

Generate synthetic data via added noise:

  • change in coloration
  • highlighting
  • occlusion from lines etc.

Take most probable set from TF response, use that to generate a FEN of the board, and bot comments on thread with FEN and link to lichess analysis

More Repositories

1

ChessboardDetect

Hodgepodge of chessboard chessboard detection algorithms on images from actual matches.
Jupyter Notebook
56
star
2

Barnes-Hut-Tree-N-body-Implementation-in-HTML-Js

A 2D N-body simulation of gravitational interactions between point particles using the Barnes-Hut algorithm.
JavaScript
50
star
3

UAV-Motion-Planner-Ensemble

A Matlab motion planner ensemble of a global Voronoi model and a local Potential Field model
MATLAB
49
star
4

StereoColorTracking

3D point tracking using stereo camera with color thresholding and disparity
Python
27
star
5

OrbitalElements

Some basic manipulation of orbital elements
Python
25
star
6

schmeckle_bot

Reddit Bot for converting Rick & Morty Schmeckles to USD
Python
24
star
7

Ngram-Tutorial

Building a basic N-gram generator and predictive sentence generator from scratch using IPython Notebook
Jupyter Notebook
16
star
8

ClickerJs

Simple clicking game to learn React
JavaScript
14
star
9

lumpsum_vs_dca

Comparing Lump Sum vs. Dollar Cost Averaging strategies, a simple experiment
Jupyter Notebook
14
star
10

MorsePy

Simple set of python functions to translate alphanumeric characters to morse code and back
Python
13
star
11

ChessboardFenTensorflowJs

Find chessboard FEN from a screenshot using TensorflowJs
JavaScript
13
star
12

existential_rick_bot

Answers questions on rickandmorty subreddit
Python
9
star
13

ThrustVectorControl

Simulating a 2D Hovering SpaceX Grasshopper with a Thrust Vector Control) engine.
Python
9
star
14

GoogleGlassHomeAutomation

say Hello Home via google glass and you can communicate with an arduino webserver, getting indoor/outdoor temperature at home or controlling the lights
Java
5
star
15

Ruby-Frequency-Analysis

Simple command-line ruby script that does word statistics on input text files, for use as test-case in rails apps
Ruby
5
star
16

Go-Computational-Fluid-Dynamics

Learning Go by trying to implement a basic computational fluid dynamics simulation
Go
4
star
17

mapf-multiagent-robot-planning

Multi-Agent PathFinding (MAPF) for 2D Robots moving inventory on a grid - Practice building environment + robots + planning + inventory management etc.
Python
4
star
18

CESMCaseMaker

Web Form GUI that fills out a template for creating a new CESM simulation
Java
4
star
19

Hanoi-PDDL-generator

N-disk Hanoi tower PDDL generator
Python
3
star
20

Barnes-Hut-N-Body-Python

Python 2D Nbody simulation w/ Barnes-Hut Quadtree division
Python
3
star
21

Nbody_cpp

Nbody C++ using Open-MPI parallel processing
C++
3
star
22

KSP-rocket-hover-controller

Using the kOS mod to programmatically control a KSP rocket and build a hover controller PID loop
Jupyter Notebook
3
star
23

Tensorflow-Cat-Dog-Classifier

Tutorial on using Tensorflow to train a cat/dog classifier, as well as building your own dataset to train on
Python
2
star
24

Nbody-OpenGL

Different OpenGL examples with the primary being Nbody (TBD)
C++
2
star
25

PCA-Image-Compression

Example image compression using Principal Component Analysis SVD to separate components of each rgb channel
MATLAB
2
star
26

ArmKinematics2D

2D Arm Kinematics & Dynamics for Golem Krang clean & snatch weightlifting
MATLAB
2
star
27

38khz-Pulser-555

Arduino + Circuit board 38 Khz Astable pulse generator ~51% duty cycle using an NE555 timer
Arduino
2
star
28

Simple-Raytracer-C

C++ basic Raytracer for a block-world
C++
2
star
29

periodicTableChooser

concept HTML page with jQuery/Autocomplete, PHP, and MySQL database of periodic elements
PHP
2
star
30

Nbody_Ruby

Following http://www.artcompsci.org/kali/vol/two_body_problem_1/title.html
Ruby
2
star
31

Flash-PID-controlled-hovercraft-toy

Using Box2d physics engine and PID controller, have a little craft go where you click it whilst hovering against gravity.
ActionScript
2
star
32

blemflark_bot

Convert Blemflarks to USD
Python
2
star
33

KalmanFilterMatlab

Basic Kalman Filter in Matlab, tested using virtual noisy data on a thrown ball in 2d
MATLAB
1
star
34

OpenGL-City-skyline-in-Ruby

Simple example based off of Pixel City
Ruby
1
star
35

Grid-based-Collision-in-Flash

Flash/Actionscript Grid-based collision detection example, runs on HTML page
CSS
1
star
36

nbodyc

Nbody gravitational star simulator in C
C
1
star
37

c3

Cloud Climate Configurator (C3)
Java
1
star
38

Nbody_Py

Yet another nbody simulation
Python
1
star
39

ChessDetect

(Deprecated: goto https://github.com/Elucidation/ChessboardDetect) Android App for finding a chessboard in a scene live and trying to predict what the piece layout is
Python
1
star
40

ArduinoPanTilt

Arduino-based pan tilt servo controller over serial
C++
1
star
41

NbodyPy_old

basic N-body simulation
Python
1
star
42

WordCount

C++ Word parsing and counting example
C++
1
star
43

ArduinoTemperatureMonitor

Tracks Indoor/Outdoor Temperature on an LCD monitor
C++
1
star
44

Unforwarder-Chrome-Extension

Replaces google search results forwarder links with original links
JavaScript
1
star
45

Boids-Vpython

Boids implementation using Visual Python
Python
1
star
46

Ultrasonic_Radar

Low-cost arduino ultrasonic radar fiddling.
C++
1
star
47

oven-temperature-readout

Oven temperature live readout using a thermocouple, a 7-segment display and an Arduino micro
Arduino
1
star
48

ArduinoTemperatureLogger

Indoor/Outdoor Temperature logging, using RTC clock and LCD screen for display
Arduino
1
star
49

maze-generator

Javascript maze generator
JavaScript
1
star
50

SeatGuru-United-Chrome-Extension

Chrome extension adding links to SeatGuru seat maps when on United seat map webpages
JavaScript
1
star