Image Classification for Playing Cards

Arjun R
The Startup
Published in
3 min readJul 30, 2020

Machine learning for classifying playing card images by suit and number

In this article I train a model using TensorFlow to detect the suit and number of playing cards given their image. I create the dataset by taking pictures of each card, then perform pre-processing and data augmentation using rotate, zoom, brighten, and shear functions. The final dataset consists of 39000, 180x180 grayscale images. I then train a convolutional neural network to classify the card images.

Dataset

To create the preliminary dataset, I simply take a single picture of each card in a 52 card deck, like so:

I then perform data augmentation using various transformation functions later on.

Code

Let’s begin the code walk through (see my github for the full project code: https://github.com/awrd2019/Playing-Cards-Computer-Vision).

First, I import all relevant libraries.

Below, I look at a single sample image from the dataset.

In the next cell, I experiment with various data augmentation functions built into TensorFlow. Feel free to adjust the values and/or add additional augmentation functions. Please see the TensorFlow.Keras ImageDataGenerator api page for more details (https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator).

Now that I have sufficiently experimented with the ImageDataGenerator and decided on a combination of transformation functions to augment the dataset, I create a new dataset of 39000 images. For each of the 52 cards, I create 750 transformed images of that card to add to the new dataset. Finally, I shuffle the new dataset before saving it.

Next, I load the dataset and split it into a train and test set.

Now I construct and train a convolutional model. Below the cell is the model summary.

During training, the training and validation accuracy both reached 99.9%. Let’s take a closer look at the loss and accuracy during the training process through the following plots.

Finally, I run the trained model on a sample of test set images. The plot below displays the sample image and the prediction of the model.

Conclusion

In this article I built a model to classify images of playing cards by suit and number.

Thank you so much for reading! I hope you enjoyed the article and would welcome any comments and suggestions.

--

--