0% found this document useful (0 votes)
4 views

sorce code .py

The document contains a Python script that preprocesses a Sudoku puzzle image, extracts numbers using OCR, and solves the puzzle using a backtracking algorithm. It includes functions for image preprocessing, number extraction, Sudoku validation, solving, and displaying the solution on the original image. The script is designed to be run with a specified image path to process and solve the Sudoku puzzle.

Uploaded by

Indira K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

sorce code .py

The document contains a Python script that preprocesses a Sudoku puzzle image, extracts numbers using OCR, and solves the puzzle using a backtracking algorithm. It includes functions for image preprocessing, number extraction, Sudoku validation, solving, and displaying the solution on the original image. The script is designed to be run with a specified image path to process and solve the Sudoku puzzle.

Uploaded by

Indira K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

import cv2

import numpy as np
import pytesseract
import matplotlib.pyplot as plt
from PIL import Image

# --- Image Preprocessing ---


def preprocess_image(image_path):
"""
Preprocesses the input image for better OCR accuracy.
"""
# Load image using OpenCV
img = cv2.imread(image_path)

# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply thresholding
_, thresh = cv2.threshold(gray, 150, 255,
cv2.THRESH_BINARY_INV)

# Optionally apply other filters to remove noise


thresh = cv2.medianBlur(thresh, 3)

return thresh, img

# --- OCR Extraction ---


def extract_numbers_from_image(thresh_img):
"""
Uses OCR to extract numbers from the thresholded image.
"""
custom_config = r'--oem 3 --psm 6'
text = pytesseract.image_to_string(thresh_img,
config=custom_config)

# Extract numbers from OCR result


lines = text.splitlines()
grid = []
for line in lines:
row = []
for char in line:
if char.isdigit():
row.append(int(char))
else:
row.append(0) # Empty space as 0
if row:
grid.append(row)

return grid

# --- Sudoku Solver (Backtracking Algorithm) ---


def is_valid(board, row, col, num):
"""
Checks if placing the number `num` in the given row and
column is valid.
"""
# Check if `num` is not in the current row
for i in range(9):
if board[row][i] == num:
return False

# Check if `num` is not in the current column


for i in range(9):
if board[i][col] == num:
return False

# Check if `num` is not in the 3x3 subgrid


start_row = (row // 3) * 3
start_col = (col // 3) * 3
for i in range(3):
for j in range(3):
if board[start_row + i][start_col + j] == num:
return False

return True

def solve_sudoku(board):
"""
Solves the Sudoku puzzle using the backtracking algorithm.
"""
for row in range(9):
for col in range(9):
if board[row][col] == 0: # Find empty spot
for num in range(1, 10): # Try digits 1-9ss
board[row][col] = num
if solve_sudoku(board):
return True
board[row][col] = 0 # Backtrack
return False
return True # Puzzle solved

def print_board(board):
"""
Prints the Sudoku board in a readable format.
"""
for row in board:
print(" ".join(str(num) for num in row))

# --- Display and Save Solutions ---


def display_sudoku_solution(board, original_img):
"""
Displays the solved Sudoku on the original image.
"""
solved_img = original_img.copy()
font = cv2.FONT_HERSHEY_SIMPLEX

# Overlay the solved numbers on the original image


for row in range(9):
for col in range(9):
if board[row][col] != 0:
cv2.putText(solved_img, str(board[row][col]), (col *
50 + 15, row * 50 + 35), font, 1, (255, 0, 0), 2)

# Show the final solved image


plt.imshow(cv2.cvtColor(solved_img, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.show()

def save_image(solved_img, output_path):


"""
Saves the solved Sudoku image to the specified output path.
"""
cv2.imwrite(output_path, solved_img)

# --- Main Function ---


def main(image_path, output_path="solved_sudoku.png"):
"""
Main function to process the Sudoku puzzle from an image,
solve it, and display the solution.
"""
# Step 1: Preprocess the image
thresh_img, original_img = preprocess_image(image_path)

# Step 2: Extract numbers from the image using OCR


grid = extract_numbers_from_image(thresh_img)

print("Original Sudoku Puzzle:")


print_board(grid)

# Step 3: Solve the Sudoku puzzle


if solve_sudoku(grid):
print("\nSolved Sudoku Puzzle:")
print_board(grid)

# Step 4: Display and save the solved Sudoku puzzle on


the original image
display_sudoku_solution(grid, original_img)
save_image(original_img, output_path)
else:
print("No solution exists.")

# --- Running the Script ---


if __name__ == "__main__":
# Replace the path with your actual Sudoku image path
image_path = "path_to_sudoku_image.jpg"
main(image_path)

You might also like