I want to create a sudoku solver using python. For this, I want to read the sudoku board from an image using an OCR. I think the best way is to split a perfectly square image of a sudoku board into 81 small images, each containing a cell of the sudoku board. I don't know how to transform an image of a sudoku board into a perfectly square image.
This image has to contain the full sudoku board an be perfectly squared. Right now this image isn't perfectly squared, so I can't divide it into 81 perfect square piece. Thank you for any help or tips.
I want to create a sudoku solver using python. For this, I want to read the sudoku board from an image using an OCR. I think the best way is to split a perfectly square image of a sudoku board into 81 small images, each containing a cell of the sudoku board. I don't know how to transform an image of a sudoku board into a perfectly square image.
This image has to contain the full sudoku board an be perfectly squared. Right now this image isn't perfectly squared, so I can't divide it into 81 perfect square piece. Thank you for any help or tips.
Share Improve this question edited 2 days ago user29691080 asked 2 days ago Ernest VandenbulckeErnest Vandenbulcke 394 bronze badges 1- 1 With the thick, black, outer border you should be able to find the positions of the top-left and bottom-right pixels to find your start and end offsets; then divide both dimensions by 3 to cut them in the middle of the black lines, then rinse and repeat for individual cells. Should minimize the cutoff on the middle rows/columns to prevent cropping the number itself – RivenSkaye Commented 2 days ago
1 Answer
Reset to default 0You can use Python's PIL
library (Pillow)
- Load the image using
PIL.Image.open()
. - Calculate the maximum side length (either width or height).
- Resize the image to a square by padding it with white (or another color) to match the largest dimension.
- Save the new image.
Here’s some sample code:
from PIL import Image
img = Image.open("original.jpg")
width, height = img.size
new_size = max(width, height)
new_img = Image.new("RGB", (new_size, new_size), (255, 255, 255))
new_img.paste(img, ((new_size - width) // 2, (new_size - height) // 2))
new_img.save("squared.jpg")