Aucune description

xword.py 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import math
  2. import cv2
  3. import numpy as np
  4. import copy
  5. import argparse
  6. def preprocess_image(original, gaussian_blur_size, adaptive_threshold_block_size, adaptive_threshold_mean_adjustment, num_dilations):
  7. img = cv2.GaussianBlur(original, (gaussian_blur_size, gaussian_blur_size), 0)
  8. img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, adaptive_threshold_block_size, adaptive_threshold_mean_adjustment)
  9. kernel = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], np.uint8)
  10. for i in range(num_dilations):
  11. img = cv2.dilate(img, kernel)
  12. return img
  13. def find_biggest_contour(img):
  14. contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  15. biggest = None
  16. max_area = 0
  17. for contour in contours:
  18. area = cv2.contourArea(contour)
  19. if area > max_area:
  20. biggest = contour
  21. max_area = area
  22. return biggest
  23. def erode_contour(img_shape, contour, kernel_size, iterations):
  24. contour_img = np.zeros(img_shape, dtype=np.uint8)
  25. cv2.drawContours(contour_img, [contour], 0, 255, -1)
  26. kernel = np.ones((kernel_size, kernel_size), dtype=np.uint8)
  27. contour_img = cv2.erode(contour_img, kernel, iterations=iterations)
  28. contour_img = cv2.dilate(contour_img, kernel, iterations=iterations)
  29. return find_biggest_contour(contour_img)
  30. def get_contour_corners(img, contour):
  31. height, width = img.shape
  32. top_left = [width, height]
  33. top_right = [-1, height]
  34. bottom_left = [width, -1]
  35. bottom_right = [-1, -1]
  36. for vertex in contour:
  37. point = vertex[0]
  38. sum = point[0] + point[1]
  39. diff = point[0] - point[1]
  40. if sum < top_left[0] + top_left[1]:
  41. top_left = point
  42. if sum > bottom_right[0] + bottom_right[1]:
  43. bottom_right = point
  44. if diff < bottom_left[0] - bottom_left[1]:
  45. bottom_left = point
  46. if diff > top_right[0] - top_right[1]:
  47. top_right = point
  48. return top_left, top_right, bottom_right, bottom_left
  49. def segment_length(p1, p2):
  50. dx = p1[0] - p2[0]
  51. dy = p1[1] - p2[1]
  52. return math.sqrt(dx ** 2 + dy ** 2)
  53. def get_longest_side(poly):
  54. previous = poly[-1]
  55. max = 0
  56. for current in poly:
  57. len = segment_length(previous, current)
  58. if len > max:
  59. max = len
  60. previous = current
  61. return max
  62. def extract_square(img, top_left, top_right, bottom_right, bottom_left):
  63. src = [top_left, top_right, bottom_right, bottom_left]
  64. longest = get_longest_side(src)
  65. dst = [[0, 0], [longest - 1, 0], [longest - 1, longest - 1], [0, longest - 1]]
  66. m = cv2.getPerspectiveTransform(np.array(src, dtype=np.float32), np.array(dst, dtype=np.float32))
  67. return cv2.warpPerspective(img, m, (int(longest), int(longest)))
  68. def get_fundamental_frequency(fft):
  69. mag = abs(fft[0:len(fft) // 2])
  70. mag[0] = 0
  71. return int(np.argmax(mag))
  72. def get_threshold_from_quantile(img, quantile):
  73. height, width = img.shape
  74. num_pixels = height * width
  75. pixels = np.sort(np.reshape(img, num_pixels))
  76. return pixels[int(num_pixels * quantile)]
  77. def extract_grid_colours(img, num_rows, num_cols, sampling_block_size_ratio):
  78. height, width = img.shape
  79. row_delta = int(height * sampling_block_size_ratio / num_rows / 2)
  80. col_delta = int(width * sampling_block_size_ratio / num_cols / 2)
  81. sampling_block_area = (2 * row_delta + 1) * (2 * col_delta + 1)
  82. grid = []
  83. for row in range(num_rows):
  84. line = []
  85. y = int(((row + 0.5) / num_rows) * height)
  86. for col in range(num_cols):
  87. sum = 0
  88. x = int(((col + 0.5) / num_cols) * width)
  89. for dy in range(-row_delta, row_delta + 1):
  90. for dx in range(-col_delta, col_delta + 1):
  91. sum += img[y + dy, x + dx]
  92. line.append(sum / sampling_block_area)
  93. grid.append(line)
  94. return grid
  95. def grid_colours_to_blocks(grid_colours, num_rows, num_cols, sampling_threshold):
  96. grid = copy.deepcopy(grid_colours)
  97. warning = False
  98. for row in range(round(num_rows / 2)):
  99. for col in range(num_cols):
  100. row2 = num_rows - row - 1
  101. col2 = num_cols - col - 1
  102. delta1 = grid_colours[row][col] - sampling_threshold
  103. delta2 = grid_colours[row2][col2] - sampling_threshold
  104. if (delta1 > 0) and (delta2 > 0):
  105. block = 0
  106. elif (delta1 < 0) and (delta2 < 0):
  107. block = 1
  108. else:
  109. warning = True
  110. if abs(delta1) > abs(delta2):
  111. block = 1 if delta1 < 0 else 0
  112. else:
  113. block = 1 if delta2 < 0 else 0
  114. grid[row][col] = grid[row2][col2] = block
  115. return warning, grid
  116. def draw_point(image, point, colour):
  117. height, width, _ = image.shape
  118. for dx in range(-10, 11):
  119. for dy in range(-10, 11):
  120. x = point[0] + dx
  121. y = point[1] + dy
  122. if (x >= 0) and (y >= 0) and (x < width) and (y < height):
  123. image[y, x] = colour
  124. def show_image(image):
  125. cv2.namedWindow('xword', cv2.WINDOW_NORMAL)
  126. cv2.imshow('xword', image)
  127. while cv2.waitKey() & 0xFF != ord('q'):
  128. pass
  129. cv2.destroyAllWindows()
  130. def extract_crossword(
  131. file_name,
  132. gaussian_blur_size=11,
  133. adaptive_threshold_block_size=11,
  134. adaptive_threshold_mean_adjustment=2,
  135. square=True,
  136. num_dilations=1,
  137. contour_erosion_kernel_size=5,
  138. contour_erosion_iterations=5,
  139. line_detector_element_size=51,
  140. sampling_block_size_ratio=0.25,
  141. sampling_threshold_quantile=0.3,
  142. sampling_threshold=None,
  143. grid_line_thickness=4,
  144. grid_square_size=64,
  145. grid_border_size=20,
  146. ):
  147. warnings = []
  148. original = cv2.imread(file_name, cv2.IMREAD_GRAYSCALE)
  149. if original is None:
  150. raise RuntimeError("Failed to load image")
  151. img = preprocess_image(original, gaussian_blur_size, adaptive_threshold_block_size, adaptive_threshold_mean_adjustment, num_dilations)
  152. biggest = find_biggest_contour(img)
  153. biggest = erode_contour(img.shape, biggest, contour_erosion_kernel_size, contour_erosion_iterations)
  154. top_left, top_right, bottom_right, bottom_left = get_contour_corners(img, biggest)
  155. img = extract_square(img, top_left, top_right, bottom_right, bottom_left)
  156. horiz_elem = cv2.getStructuringElement(cv2.MORPH_RECT, (line_detector_element_size, 1))
  157. horiz_lines = cv2.erode(img, horiz_elem)
  158. horiz_lines = cv2.dilate(horiz_lines, horiz_elem)
  159. vert_elem = cv2.getStructuringElement(cv2.MORPH_RECT, (1, line_detector_element_size))
  160. vert_lines = cv2.erode(img, vert_elem)
  161. vert_lines = cv2.dilate(vert_lines, vert_elem)
  162. row_fft = np.fft.fft(np.sum(horiz_lines, axis=1))
  163. col_fft = np.fft.fft(np.sum(vert_lines, axis=0))
  164. num_rows = get_fundamental_frequency(row_fft)
  165. num_cols = get_fundamental_frequency(col_fft)
  166. if square and (num_rows != num_cols):
  167. warnings.append("Crossword is not square")
  168. block_img = extract_square(original, top_left, top_right, bottom_right, bottom_left)
  169. if sampling_threshold is None:
  170. sampling_threshold = get_threshold_from_quantile(block_img, sampling_threshold_quantile)
  171. else:
  172. sampling_threshold = sampling_threshold
  173. grid_colours = extract_grid_colours(block_img, num_rows, num_cols, sampling_block_size_ratio)
  174. warning, grid = grid_colours_to_blocks(grid_colours, num_rows, num_cols, sampling_threshold)
  175. if warning:
  176. warnings.append("Some blocks may be the wrong colour")
  177. step = grid_square_size + grid_line_thickness
  178. grid_height = num_rows * step + grid_line_thickness
  179. grid_width = num_cols * step + grid_line_thickness
  180. output = np.full([2 * grid_border_size + grid_height, 2 * grid_border_size + grid_width], 255, dtype=np.uint8)
  181. cv2.rectangle(output, (grid_border_size, grid_border_size), (grid_border_size + grid_width - 1, grid_border_size + grid_height - 1), 0, -1)
  182. for row in range(num_rows):
  183. y = row * step + grid_line_thickness + grid_border_size
  184. for col in range(num_cols):
  185. if grid[row][col] == 0:
  186. x = col * step + grid_line_thickness + grid_border_size
  187. cv2.rectangle(output, (x, y), (x + grid_square_size - 1, y + grid_square_size - 1), 255, -1)
  188. _, png = cv2.imencode('.png', output)
  189. return png.tobytes(), warnings