Computer Vision + TensorFlow CNN to detect chess pieces from online chessboard screenshots
Hi guys, I created this bot to reply to chess puzzle images on r/chess (introduction Xpost there) with the predicted Forsyth-Edwards Notation for the board layout. I wrote this to learn TensorFlow and solve a pet peeve at the same time.
TL;DR:
Python script that uses computer vision to split up images into 32x32 grayscale tiles as input, collect ~9400 tiles of training data. Train a convolutional neural network which is almost a verbatim copy of this tutorial.
Make predictions on r/chess image posts, these predictions are put together into a FEN for the entire board, and then provides a link to an online chess analysis of that board layout.
There are 4 IPython notebooks in the Github with code and documentation. I tried to make it more accessible by documenting the learning process with fun images.
tensorflow_chessbot.ipynb - Computer Vision
Here is a screenshot with the detected lines of the chessboard overlaid, showing where we'll cut the image into tiles.
tensorflow_generate_training_data.ipynb - 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.
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.
tensorflow_learn.ipynb - 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.
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
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 ~78% success rate on 71 chess subreddit posts, good enough to make a first draft Reddit bot.
Thanks for taking the time to read this, hope this is interesting to some of you. You can see some of my recent replies on u/ChessFenBot
Posted Feb 15, 2016, 2:32 AM UTC · edited
Seems like you're using a hammer to crack an egg here. Since the images are so uniform, feels like you should be able to do something much simpler and hand-tuned to beat this, e.g. find rooks by their crenelated head, find knights by their lack of symmetry.
Less fun, but I bet it's going to be easier than looking for a big and varied enough dataset to make this work well.
Maybe, but having done a lot of machine vision work before the great CNN revolution, I can say that featuring engineering is quite difficult, and with proper artificially generated training sets with various noise (affine distortions, etc), I think the ML approach probably is less total work. If not, I bet it's closer than you imagine, and it's definitely requires less 'invention', in that the basic methodology follows any visual recognition problem, so it's probably lower risk as well.
For someone learning tensorflow, I'd be terrified to do the amount of work they did. Very impressive to me, mostly because I'm just not there yet.
I'm with u/sobe86 on this, the ML solution wasn't necessary. Fun and interesting, but I think differentiating between six B/W figures on a B/W grid can be solved by traditional CV.
Very thorough and interesting, though.
I see this as the best way to solve the problem. Rather than saying what you think it looks like offhand, if you can't provide a specific way that your thought of method would would, then general commentary is unlikely to help someone who has recently become an expert in this domain (and written a very impressive solution).
The poster did this because it was the most exciting way to solve the problem, it's not the first thing he should have tried if he was seriously trying to make this as good as possible with the least amount of effort. This is machine learning 101 - start simple, THEN get complicated. Convolutional neural networks are the extreme, they should be used for image tasks that require hierarchical reasoning - this dataset does NOT fit that category - it's extremely uniform.
Why not try nearest neighbours, why not try a little feature engineering? Currently this guys model scores ~80% on test data - but it's not clear to me whether that's a good performance, because there's no simple benchmark.
[deleted]
Good point, you're right. I really wanted to learn tensorflow and build a basic ML model so that was 99% of the reason I chose it. I did spend a little time looking into the dataset; seeing the different piece sets and themes out there, some of them were different enough that it seemed like I'd get bogged down in the details.
Anecdotely, it felt like the ML model lets me trade developer time for code complexity vs. other approaches (given enough data, in this case same effort for both so far).
A fun thing would be to try (as you suggested below as well) a KNN type approach for each piece as well, and have it and the ML model run on tiles as a fallback.
I'm just curious, what is the difficulty with getting a 99%+ correct identification rate? What is the thing that's stopping you from training it to have a higher success rate? I would have thought that chess pieces would be relatively easy to train compared to real life photos etc. I'm asking because I'm also learning TensorFlow (and machine learning in general) at the moment.
No worries. Background, the training data is from around 6 different most common piece sets and board themes from lichess.org and chess.com. There are about 280 combinations on lichess for example and I only covered around 20 of them. For each piece set and board theme I generated ~5 boards, giving around 320 tiles per theme, a very small amount of data actually.
This is because I had to manually switch themes/piecesets since I couldn't find a way to programmatically change themes (cookies were generated & locked to theme, I may figure out something there at some point), after each theme/piece set switch I could programmatically generate several boards (~5-10 boards, 320-640 tiles) from FENs and screenshot them. This problem would affect KNN & other statistical approaches the same unfortunately.
A better solution will be to download their github board/pieceset pngs/svgs and generate the tiles for all 280 combinations. I plan to do this when I have time, this will be a great opportunity to try out KNN also
If you look through my post history, in every case of an image that uses a piece set that is or pretty similar to one of those piece sets, the certainty is 99.9%+, as you'd expect. It seems to handle arbitrary board themes I haven't trained with without issue.
The 1/5 cases where the training fails appear to all be because the piece sets are not in my training set and look wildly different, for example these are two where the bot failed due to lack of training data for that piece set:
Mistook black pawns for bishops: https://www.reddit.com/r/chess/comments/3z73kz/white_to_play_and_mate_in_3_judit_polgar_vs/
Mistook rooks and kings for queens: https://www.reddit.com/r/chess/comments/40ehtx/white_to_play_mate_in_6/
The last one is telling, because those piece sets are different enough from the ones trained with. Look at the king/queen/knight and other pieces here vs here
Thanks for that. I wonder why you can't access a database of images somehow (or ask the community to submit them, labelled) to get enough training data. But in any case, it makes perfect sense, I thought your solution should work.