This project detects a Sudoku puzzle from an image, recognizes digits using a trained CNN, solves the puzzle, and overlays the solution back onto the image.
sudokuMain.py: End-to-end pipeline that reads an image (optionally from PostgreSQL), detects the board, runs digit recognition, solves the puzzle, and shows the overlay.sudokuMain2.py: Alternate pipeline usingutils2.pyhelper functions.sudokuSolver.py: Backtracking Sudoku solver.utils.py: Image preprocessing, contour detection, digit extraction, and rendering helpers.utils2.py: Alternate set of image utilities used bysudokuMain2.py.Resources/model_trained.h5: Trained CNN model for digit recognition.
- Python 3.9+ recommended
- A working camera or image file for testing
- (Optional) PostgreSQL if using the image-from-DB flow in
sudokuMain.py
-
Create and activate a virtual environment.
-
Install dependencies.
pip install numpy opencv-python tensorflow psycopg2 h5pyIf you are on Windows and psycopg2 fails, use:
pip install psycopg2-binary- Put an image named
1.jpg(or update the filename) inResources/. - Update the path in the script:
sudokuMain.pyusespathImage = "Resources/1.jpg"sudokuMain2.pyusespathImage = "Resources/1.jpeg"
- Run either script:
python sudokuMain.pyor
python sudokuMain2.pyYou should see OpenCV windows showing the detected digits, solved digits, and the final overlay.
sudoMain.py (typo: sudokuMain.py) includes a helper to fetch an image from PostgreSQL and save it to Resources/1.jpg.
To use it:
- Ensure your DB has a table with an image byte column (see
read_image_from_dbinsudokuMain.py). - Update the DB connection settings in
sudokuMain.py:databaseuserpasswordhost(if not local)
- Run:
python sudokuMain.pyNote: Do not commit real credentials. Use environment variables or a local config file if you need to store secrets.
- Preprocess the image (grayscale, blur, adaptive threshold).
- Find the biggest contour and warp it into a square.
- Split into 81 cells and run the CNN to recognize digits.
- Solve the Sudoku using backtracking.
- Overlay the solved digits back onto the original image.
- If no Sudoku is found, try a clearer image with higher contrast.
- If TensorFlow fails to load the model, verify
Resources/model_trained.h5exists and matches your TF version. - If the prediction threshold seems too strict, check the
getPrediction/getPredectionlogic in the utils files. - OpenCV windows might not appear in some IDEs; run from a terminal.
utils.pyandutils2.pyare slightly different implementations. Stick to one pipeline for consistency.- The solver (
sudokuSolver.py) operates on a 9x9 array of integers with zeros as blanks.
No automated tests are included yet. If you add tests, consider unit tests for:
- Sudoku solver correctness
- Image preprocessing and contour selection
- Digit classifier output shape and thresholds
No license file is included. Add a LICENSE if you plan to share or distribute the project.