Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

utils.py 8.7 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
  1. import cv2
  2. import numpy as np
  3. import tensorflow as tf
  4. import matplotlib.pyplot as plt
  5. from PIL import Image
  6. # Preprocessing the Sudoku Grid
  7. def preprocess_grid(image:np.array, resize_dim:tuple=(450,450)) -> np.array:
  8. """
  9. A function that preprocesses an image by converting it to grayscale, resizing it, and applying Gaussian blur.
  10. Parameters:
  11. image (np.array): The input image to be processed.
  12. Returns:
  13. np.array: The preprocessed image as a NumPy array.
  14. """
  15. height = resize_dim[0]
  16. width = resize_dim[1]
  17. gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  18. resized_image = cv2.resize(gray_image, (height,width))
  19. blurred_image = cv2.GaussianBlur(resized_image, (5,5), cv2.BORDER_DEFAULT)
  20. final_image = blurred_image
  21. return final_image
  22. def get_contour_corners(image:np.array) -> np.array:
  23. """
  24. A function that takes an image as input and returns the corners of the largest contour in the image.
  25. Parameters:
  26. image (np.array): The input image as a NumPy array.
  27. Returns:
  28. np.array: The corners of the largest contour in the image as a NumPy array.
  29. """
  30. threshold = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 13, 2)
  31. contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  32. largest_contour = max(contours, key=cv2.contourArea)
  33. epsilon = 0.1 * cv2.arcLength(largest_contour, True)
  34. contour_corners = cv2.approxPolyDP(largest_contour, epsilon, True)
  35. return contour_corners
  36. def sort_corners(corners:np.array) -> np.array:
  37. """
  38. Sorts the corners in clockwise order starting from the top-left corner.
  39. """
  40. sorted_corners = np.zeros((4,2), dtype=np.float32)
  41. corners = corners.reshape((4,2))
  42. sorted_corners[0] = corners[np.argmin(np.sum(corners, axis=1))]
  43. sorted_corners[1] = corners[np.argmin(np.diff(corners, axis=1))]
  44. sorted_corners[2] = corners[np.argmax(np.sum(corners, axis=1))]
  45. sorted_corners[3] = corners[np.argmax(np.diff(corners, axis=1))]
  46. return np.float32(sorted_corners)
  47. def target_corners(image:np.array) -> np.array:
  48. """
  49. A function that calculates the corners of the target rectangle based on the input image dimensions.
  50. Parameters:
  51. image (np.array): The input image as a NumPy array.
  52. Returns:
  53. np.array: The corners of the target rectangle as a NumPy array.
  54. """
  55. resize_dim = (image.shape[0], image.shape[1])
  56. height, width = resize_dim
  57. target_corners = np.array([[0, 0], [width, 0], [width, height], [0, height]])
  58. return np.float32(target_corners)
  59. def warp_image(image:np.array, sorted_corners:np.array, targeted_corners:np.array) -> np.array:
  60. """
  61. Warps an image using perspective transformation based on the given sorted corners and targeted corners.
  62. Args:
  63. image (np.array): The input image as a NumPy array.
  64. sorted_corners (np.array): The sorted corners of the image as a NumPy array.
  65. targeted_corners (np.array): The target corners for the perspective transformation as a NumPy array.
  66. Returns:
  67. np.array: The warped image as a NumPy array.
  68. """
  69. perspective_matrix = cv2.getPerspectiveTransform(sorted_corners, targeted_corners)
  70. warped_image = cv2.warpPerspective(image, perspective_matrix, image.shape[:2])
  71. return warped_image
  72. def divide_into_9x9_boxes(sudoku_grid:np.array) -> list:
  73. """
  74. Divides a Sudoku grid into 9x9 boxes and returns a list of these cropped boxes.
  75. Args:
  76. sudoku_grid (np.array): The input Sudoku grid as a NumPy array.
  77. Returns:
  78. list: A list containing the 9x9 cropped boxes from the Sudoku grid.
  79. """
  80. # Get image dimensions
  81. height, width = sudoku_grid.shape[:2]
  82. # Calculate box size
  83. box_height = height // 9
  84. box_width = width // 9
  85. # Initialize list to store cropped boxes
  86. boxes = []
  87. # Iterate over the rows and columns to extract 9x9 boxes
  88. for i in range(9):
  89. for j in range(9):
  90. # Calculate coordinates for each box
  91. y_start = i * box_height
  92. y_end = (i + 1) * box_height
  93. x_start = j * box_width
  94. x_end = (j + 1) * box_width
  95. # Crop box from image
  96. box = sudoku_grid[y_start:y_end, x_start:x_end]
  97. boxes.append(box)
  98. return boxes
  99. def crop_boxes(box_images:list) -> list:
  100. """
  101. Given a list of box images, this function crops each image to a specified region and returns a list of the cropped images.
  102. :param box_images: A list of images representing sudoku boxes.
  103. :type box_images: list
  104. :return: A list of cropped images.
  105. :rtype: list
  106. """
  107. left = 3
  108. upper = 3
  109. right = 47
  110. lower = 47
  111. cropped_boxes = []
  112. for box in box_images:
  113. # Crop the image
  114. box = Image.fromarray(box)
  115. cropped_image = box.crop((left, upper, right, lower))
  116. cropped_boxes.append(cropped_image)
  117. return cropped_boxes
  118. def plot_sudoku_boxes(box_images:list) -> None:
  119. """
  120. Plots sudoku boxes using the input list of box images.
  121. Args:
  122. box_images (list): A list of images representing sudoku boxes.
  123. Returns:
  124. None
  125. """
  126. fig, axs = plt.subplots(9, 9, figsize=(3, 3))
  127. # Iterate over each subplot and image
  128. for ax, image in zip(axs.ravel(), box_images):
  129. ax.imshow(image, cmap='gray') # Display the image in grayscale
  130. ax.axis('off') # Turn off axis labels and ticks
  131. # Adjust layout and display the figure
  132. plt.tight_layout()
  133. plt.show()
  134. # Preprocess for CNN
  135. def image_to_pixels(image:np.array, resize_dim:tuple=(28,28)) -> np.array:
  136. """
  137. A function that converts an image to grayscale, equalizes it, resizes it, and returns the processed image as a NumPy array.
  138. Parameters:
  139. image (np.array): The input image to be processed.
  140. Returns:
  141. np.array: The processed image as a NumPy array.
  142. """
  143. if len(image.shape) >= 3:
  144. gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  145. equalized_image = cv2.equalizeHist(gray_image)
  146. image = cv2.resize(equalized_image, resize_dim)
  147. else:
  148. print('Already grayscale')
  149. equalized_image = cv2.equalizeHist(image)
  150. image = cv2.resize(equalized_image, resize_dim)
  151. return image
  152. def preprocess_pixels(image:np.array, resize_dim:tuple=(28,28)) -> np.array:
  153. """
  154. Resizes and normalizes an image and returns the processed image as a NumPy array.
  155. Parameters:
  156. image (np.array): The input image to be preprocessed.
  157. Returns:
  158. np.array: The preprocessed image as a NumPy array.
  159. """
  160. normalized_image = tf.keras.utils.normalize(image, axis=1)
  161. preprocessed_image = np.array(normalized_image).reshape(-1, resize_dim[0], resize_dim[1], 1)
  162. return preprocessed_image
  163. def predict_sudoku_grid(box_images:list, model:tf.keras.Model, verbose:int=0) -> np.array:
  164. """
  165. Predicts the values of a Sudoku grid based on a list of box images using a trained model.
  166. Args:
  167. box_images (list): A list of images representing Sudoku boxes.
  168. model (tf.keras.Model): The trained model used for prediction.
  169. verbose (int, optional): If set to 1, prints the prediction for each box. Defaults to 0.
  170. Returns:
  171. np.array: A 9x9 NumPy array representing the predicted Sudoku grid.
  172. """
  173. sudoku_grid = np.zeros(81)
  174. for index, box in enumerate(box_images):
  175. box = np.array(box)
  176. box = cv2.resize(box, (28,28))
  177. box = preprocess_pixels(box)
  178. prediction = model.predict(box, verbose=0)
  179. if verbose == 1:
  180. print(f'Box {index+1}: {prediction.round(3)}')
  181. predicted_probability = prediction.max()
  182. if predicted_probability < .6:
  183. prediction_label = 0
  184. else:
  185. prediction_label = prediction.argmax() + 1
  186. sudoku_grid[index] = prediction_label
  187. return sudoku_grid.reshape((9,9))
  188. # Solve Sudoku
  189. def possible(y, x, n, sudoku_grid):
  190. for i in range(9):
  191. if sudoku_grid[i][x] == n:
  192. return False
  193. for i in range(9):
  194. if sudoku_grid[y][i] == n:
  195. return False
  196. x0 = (x//3) * 3
  197. y0 = (y//3) * 3
  198. for i in range(3):
  199. for j in range(3):
  200. if sudoku_grid[y0+i][x0+j] == n:
  201. return False
  202. return True
  203. def solve_sudoku(sudoku_grid):
  204. for y in range(9):
  205. for x in range(9):
  206. if sudoku_grid[y][x] == 0:
  207. for n in range(1, 10):
  208. if possible(y, x, n, sudoku_grid):
  209. sudoku_grid[y][x] = n
  210. solve_sudoku(sudoku_grid)
  211. sudoku_grid[y][x] = 0
  212. return
  213. print(sudoku_grid)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...