Visual Sudoku AI and its functioning

Original Source Here

Visual Sudoku AI and its functioning

But,what’s a Sudoku?

A Sudoku is a 9×9 grid which we have to fill from number ranging between 1–9. Pretty easy right, but there’s a catch. No duplicates should occur in any row and or any column.

Sample image of Sudoku

Steps involved

The whole model is divided into four major steps:

  • Preprocessing and extracting the Sudoku
  • Building and training the predictive model to classify the given digits in Sudoku
  • Solving the Sudoku
  • Visualising output

Importing essential libraries

We need to import the required libraries to make sure our code works.

Preprocessing and extracting the Sudoku

Firstly, we import the Sudoku image and change its colour channel to grey and apply Gaussian blur to it. We apply blur to remove some fine noise that may interfere with the Sudoku extraction.

Now, we apply a threshold filter and invert the bits of the image to make it easier to extract contour

We start capturing the contours one by one and select the one which has 4 vertices.

Time to visualise the extracted contour of the Sudoku

Looking at this Sudoku, don’t you think it’s a little warped and skewed. So, we apply bird’s eye view transformation.

Training and executing the model

Now that we have our Sudoku extracted, we need to extract the numbers out of it. We accomplish this by using a Convolutional Neural Network. It classifies and outputs the given digits of the Sudoku.

Time for training, we use the MNIST dataset to train our model and achieve a validation accuracy of 99%.

Finally, using the model to classify the digits in the Sudoku

Solving the Sudoku

We use a backtracking algorithm to solve our given Sudoku. It does so by looking at every possible way and choosing the right one. This is very naive and is very time expensive. So we use memoization to keep track of all the possibilities we have visited so we don’t have to recalculate them again.

The Output

The output is presented in an image form that shows the solved Sudoku.


This app is also deployed online using Streamlit, but it’s a prototype and is not very reliable:

You can check out GitHub repository:


Trending AI/ML Article Identified & Digested via Granola by Ramsey Elbasheer; a Machine-Driven RSS Bot

%d bloggers like this: