Git Product home page Git Product logo

ai_sudoku's Introduction

AI_Sudoku

forthebadge made-with-python forthebadge cc-0

GUI Smart Sudoku Solver that tries to extract a sudoku puzzle from a photo and solve it.

Table Of Contents:

Installation

Usage

Working

ToDo

Contributing

Installation

  1. Download and install Python3 from here

  2. I recommend using virtualenv. Download virtualenv by opening a terminal and typing:

    pip install virtualenv
  3. Create a virtual environment with the name sudokuenv.

    • Windows
    virtualenv sudokuenv
    cd sudokuenv/Scripts
    activate
    • Linux:
    source sudokuenv/bin/activate
  4. Clone this repository, extract it if you downloaded a .zip or .tar file and cd into the cloned repository.

    • For Example:
    cd A:\AI_Sudoku-master
  5. Install the required packages by typing:

    pip install -r requirements.txt

Usage

  • Before running the application, know that you can set the modeltype variable in Run.py to either "CNN" or "KNN" to choose the Convolutional Neural Network or the K Nearest Neighbours Algorithm for Recognition. By default it is set to "KNN" and I got a way higher accuracy using KNN itself, so I would recommend that you don't change it.

    '''Run this file to run the application'''
    from MainUI import MainUI
    from CNN import CNN
    from KNN import KNN
    import os
    # Change the model type variable value to "CNN" to use the Convolutional Neural Network
    # Change the model type variable value to "KNN" to use the K Nearest Neighbours Classifier
    modeltype = "KNN"
  • Type the below command to run the Application. You need to be connected to the Internet and it might take 5-10 minutes to create the knn.sav file so please wait patiently. This delay is only during the first run as once created, the application will use the local file

    python Run.py
  • The GUI Homepage that opens up as soon as you run the application.

  • You need to select an image of a Sudoku Puzzle through the GUI Home Page.

  • Once you press Next, a number of stages of image processing take place which are displayed by the GUI leading up to recognition. Here are snapshots of two of the stages:

  • For recognition, a CNN or KNN can be used. This option can be toggled as mentioned in the first point. Once recognized, the board is displayed and you can rectify any wrongly recognized entries in the board.

  • Finally click on reveal solution to display the solution.

Working

Image Preprocessing

  • Gaussian Blurring Blurring using a Gaussian function. This is to reduce noise and detail.

  • Adaptive Gaussian Thresholding Adaptive thresholding with a Gaussian Function to account for different illuminations in different parts of the image.

  • Inverting to make the digits and lines white while making the background black.

  • Dilation with a plus shaped 3X3 Kernel to fill out any cracks in the board lines and thicken the board lines.

  • Flood Filling Since the board will probably be the largest blob a.k.a connected component with the largest area, floodfilling from different seed points and finding all connected components followed by finding the largest floodfilled area region will give the board.

  • The largest blob a.k.a the board is found after the previous step. Let's call this the outerbox

  • Eroding the grid a bit to undo the effects of the dilation on the outerbox that we did earlier.

  • Hough Line Transform to find all the lines in the detected outerbox.

  • Merging related lines. The lines found by the Hough Transform that are close to each other are fused together.

  • Finding the Extreme lines . We find the border lines by choosing the nearest line from the top with slope almost 0 as the upper edge, the nearest line from the bottom with slope almost 0 as the lower edge, the nearest line from the left with slope almost infinity as the left edge and the nearest line from the right with slope almost infinity as the right edge.

  • Finding the four intersection points. The four intersection points of these lines are found and plotted along with the lines.

  • Warping perspective. We find the perspective matrix using the end points, correct the perspective and crop the board out of the original image.

  • Thresholding and Inverting the grid. The cropped image from the previous step is adaptive thresholded and inverted.

  • Slicing the grid into 81 slices to get images of each cell of the Sudoku board.

  • Blackfilling and centering the number. Any white patches other than the number are removed by floodfilling with black from the outer layer points as seeds. Then the approximate bounding box of the number is found and centered in the image.

Recognition

Convolutional Neural Network

Read about CNNs here

  • Layers A Convolution Layer, a Max Pooling layer flattened into a hidden layer followed by some Dropout Regularization, another hidden layer and finally the output layer. Each of the inner layer uses ReLu while the output layer uses softmax.
  • Compilation Adam optimizer and sparse categorical cross entropy loss.
  • Training The model is trained on the MNIST handwritten digits dataset which has around 70,000 28X28 images.
  • Accuracy Around 98 percent accuracy on the test set.

K Nearest Neighbours

Read about KNN here

  • K value used is 3.
  • Training Trained on the MNIST handwritten digits dataset which has around 70,000 28X28 images.
  • Accuracy Around 97 percent accuracy on the test set.

ToDo

  • Improve Accuracy.
  • Resolve Bugs/Issues if any found.
  • Optimize Code to make it faster.

Contributing

Contributions are welcome ๐Ÿ˜„

Pull requests

Just a few guidelines:

  • Write clean code with appropriate comments and add suitable error handling.
  • Test the application and make sure no bugs/ issues come up.
  • Open a pull request and I will be happy to acknowledge your contribution after some checking from my side.

Issues

If you find any bugs/issues, raise an issue.

ai_sudoku's People

Contributors

dependabot[bot] avatar neeru1207 avatar tilaksn avatar vj68 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ai_sudoku's Issues

Expose functionality via REST API

Awesome project, I'm just wondering, is there appetite to wrap the core functionality into a Flask rest endpoint? or at least point me to the core functionality required to expose said core functionality into a rest endpoint?

import error

Unable to import 'RecognizeAndConstructBoard',
Unable to import 'BoardExtractor'
Unable to import 'SudokuSolver'

How do I run this code in Mac?

I am new to GitHub and don't really know how to run this code in MacBook.I tried downloading zip file and running the .py extension files in Pycharm but getting many errors.Can you please guide me?

opencv-contrib-python==4.1.1.26

Error could not find a version that satisfies the requirement opencv-contrib-python==4.1.1.26 (from -r requirements.txt(line 12))

member

G:\Python\python.exe F:/DACS5/copy/AI_Sudoku/MainUI.py
Traceback (most recent call last):
File "F:\DACS5\copy\AI_Sudoku\MainUI.py", line 7, in
from RecognizeAndConstructBoard import ConstructGrid
File "F:\DACS5\copy\AI_Sudoku\RecognizeAndConstructBoard.py", line 9, in
from Recognizer import DigitRecognizer
File "F:\DACS5\copy\AI_Sudoku\Recognizer.py", line 6, in
import tensorflow as tf
File "G:\Python\lib\site-packages\tensorflow_init_.py", line 473, in
keras._load()
File "G:\Python\lib\site-packages\tensorflow\python\util\lazy_loader.py", line 41, in load
module = importlib.import_module(self.name)
File "G:\Python\lib\importlib_init
.py", line 126, in import_module
return bootstrap.gcd_import(name[level:], package, level)
File "G:\Python\lib\site-packages\keras_init
.py", line 25, in
from keras import models
File "G:\Python\lib\site-packages\keras\models_init
.py", line 18, in
from keras.engine.functional import Functional
File "G:\Python\lib\site-packages\keras\engine\functional.py", line 25, in
from keras.engine import base_layer
File "G:\Python\lib\site-packages\keras\engine\base_layer.py", line 43, in
from keras.mixed_precision import loss_scale_optimizer
File "G:\Python\lib\site-packages\keras\mixed_precision\loss_scale_optimizer.py", line 20, in
from keras.optimizer_experimental import optimizer as optimizer_experimental
File "G:\Python\lib\site-packages\keras\optimizer_experimental\optimizer.py", line 649, in
tf.internal.saved_model.load.register_revived_type(
File "G:\Python\lib\site-packages\tensorflow\python\saved_model\revived_types.py", line 133, in register_revived_type
raise AssertionError(f"Duplicate registrations for type '{identifier}'")
AssertionError: Duplicate registrations for type 'experimentalOptimizer'

Process finished with exit code 1

KeyError

2023-05-06 10:39:50.429221: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023-05-06 10:39:51.623062: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT
Saved KNN Classifier not found....
Downloading MNIST Data, training KNN classifier and saving as knn.sav......
Kindly wait for a few minutes............
/usr/local/lib/python3.10/dist-packages/sklearn/datasets/_openml.py:968: FutureWarning: The default value of parser will change from 'liac-arff' to 'auto' in 1.4. You can set parser='auto' to silence this warning. Therefore, an ImportError will be raised from 1.4 if the dataset is dense and pandas is not installed. Note that the pandas parser may return different data types. See the Notes Section in fetch_openml's API doc for details.
warn(
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py", line 3802, in get_loc
return self._engine.get_loc(casted_key)
File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 5745, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 5753, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 34540

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/content/AI_Sudoku/Run.py", line 19, in
knnobj.skl_knn()
File "/content/AI_Sudoku/KNN.py", line 40, in skl_knn
fifty_x, fifty_y = self.mk_dataset(50000)
File "/content/AI_Sudoku/KNN.py", line 28, in mk_dataset
train_img = [self.data[i] for i in self.indx[:size]]
File "/content/AI_Sudoku/KNN.py", line 28, in
train_img = [self.data[i] for i in self.indx[:size]]
File "/usr/local/lib/python3.10/dist-packages/pandas/core/frame.py", line 3807, in getitem
indexer = self.columns.get_loc(key)
File "/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py", line 3804, in get_loc
raise KeyError(key) from err
KeyError: 34540

No module named 'tkinter'

(sudokuenv) C:\Users\Bruno\sudokuenv\AI_Sudoku-master>python Run.py
Traceback (most recent call last):
File "Run.py", line 2, in
from MainUI import MainUI
File "C:\Users\Bruno\sudokuenv\AI_Sudoku-master\MainUI.py", line 4, in
from tkinter import *
ModuleNotFoundError: No module named 'tkinter'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.