File name: puzzleSolver.py import numpy as np import cv2 import pytesseract from PIL…
Private research annotation
Sign in to add a private research label or note.
- User
File name: puzzleSolver.py
import numpy as np import cv2 import pytesseract from PIL import Image import crossword
Load the image
img = cv2.imread('puzzle_image.jpg')
Pre-process the image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
Detect the puzzle region
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contour = max(contours, key=cv2.contourArea) x, y, w, h = cv2.boundingRect(contour)
Crop the puzzle region
puzzle_region = img[y:y+h, x:x+w]
Use OCR to extract the puzzle grid and letters
text = pytesseract.image_to_string(puzzle_region, lang='eng', config='--psm 11') puzzle_grid = [] for line in text.split('\n'): puzzle_grid.append([char for char in line if char.isalpha()])
given_letters = ['A', 'B', 'C'] # Example given letters
def highlight_letters(puzzle_region, given_letters): # Convert the puzzle region to grayscale gray = cv2.cvtColor(puzzle_region, cv2.COLOR_BGR2GRAY)
code# Create a mask for the given letters mask = np.zeros((gray.shape[0], gray.shape[1]), dtype=np.uint8) for letter in given_letters: contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: x, y, w, h = cv2.boundingRect(contour) cv2.rectangle(mask, (x, y), (x+w, y+h), 255, -1) # Highlight the given letters highlighted_puzzle = cv2.addWeighted(gray, 1, mask, 0.5, 0) return highlighted_puzzledef solve_puzzle(puzzle_grid, given_letters): # Create a crossword object crossword_puzzle = crossword.Crossword(puzzle_grid)
code# Set the given letters as constraints for letter in given_letters: crossword_puzzle.set_constraint(letter) # Solve the puzzle solution = crossword_puzzle.solve() return solutionRun the program
highlighted_puzzle = highlight_letters(puzzle_region, given_letters) solution = solve_puzzle(puzzle_grid, given_letters)
print("Highlighted Puzzle:") print(highlighted_puzzle) print("Solution:") print(solution)
- Assistant
- User
- Assistant
- User
File "C:\Users\chops\Desktop\crossword puzzle solver\puzzleSolver.py", line 9 img = cv2.imread(‘puzzle_image.jpg’) ^ SyntaxError: invalid character '‘' (U+2018)
- Assistant
- User
File "C:\Users\chops\Desktop\crossword puzzle solver\puzzleSolver.py", line 9 img = cv2.imread(‘puzzle_image.jpg’) ^ SyntaxError: invalid character '‘' (U+2018)
- Assistant