def return_question_and_answer(): answer = return_answer() size = answer.size question = [] for i in xrange(size**2): line = [] for j in xrange(size**2): line.append(answer.board[i][j]) question.append(line) visited = [] for i in xrange(size**2): visited.append([0] * size**2) counter = 0 while counter < size**4: i = random.randrange(size**2) j = random.randrange(size**2) if visited[i][j] == 0: counter += 1 visited[i][j] = 1 temp = question[i][j] question[i][j] = 0 solution = [] for k in xrange(size**2): solution.append(question[k][:]) solve = 0 for s in sudoku_solver.solve_sudoku((size, size), solution): solve += 1 if solve != 1: question[i][j] = temp return question, answer.board
def __init__(self, master): self.master = master self.canvas = Canvas(master, width=WIDTH, height=HEIGHT, bg="white") self.canvas.pack(fill=BOTH, side=TOP) # Buttons self.check_mode = False self.check_button = Button(master, text="Check", fg='green', command=self.check_sudoku) self.check_button.pack(side=RIGHT) self.solve_button = Button(master, text="Solve", fg='blue', command=self.draw_solution) self.solve_button.pack(side=RIGHT) self.hint_button = Button(master, text="Hint", fg='purple', command=self.give_hint) self.hint_button.pack(side=LEFT) # Get a sudoku and its solution. self.original_sudoku = sudoku_solver.randomized_sudoku( number_of_removed_cells) # Original self.user_sudoku = deepcopy(self.original_sudoku) # User will change self.sudoku_solution = sudoku_solver.solve_sudoku( deepcopy(self.user_sudoku)) # Solution of the sudoku self.canvas.bind("<Button-1>", self.canvas_click) self.canvas.bind("<Key>", self.canvas_key) # Start some variables self.row, self.column = 0, 0 self.start_time = time.time() # Set up the clock self.clock = Label(master) self.clock.pack(side=BOTTOM) self.__draw_clock() self.__draw_sudoku()
def run_pipeline(self, image): """ Run pipeline for sudoku solver @param image: the sudoku image @return: solution """ image_copy = image.copy() grayscale = self.image_processor.convert_to_grayscale(image_copy) crop_rect = self.get_coordinates_of_largest_contour(image_copy) sudoku_roi = self.crop_and_wrap_sudoku_roi(grayscale, crop_rect) plot_image(sudoku_roi, 'roi') squares = self.get_digit_coordinates_from_sudoku_roi(sudoku_roi) mask_digits = [] labels = [] mask_dict = dict() for i in range(len(squares)): mask, target_label = self.extract_one_digit(sudoku_roi, squares[i]) labels.append(target_label) if target_label is not None: mask = self.__pad_to_central(mask) mask_digits.append(mask) mask_dict[str(i)] = mask map = np.zeros(shape=(1, 81)) if len(mask_digits) > 0: mask_dict = { k: cv2.resize(x, (28, 28)) for k, x in mask_dict.items() } # plot_images(mask_digits,'digits') mask_digits = np.array(mask_digits) result_dict = predict_images(mask_dict, model, validata) for k, v in result_dict.items(): map[0][int(k)] = v map = map.reshape(9, 9) can_solve = solve_sudoku(map) if can_solve: print(map) display_solution(map) else: print("no solution")
def return_question_and_answer(): answer = return_answer() size = answer.size question = [] for i in xrange (size**2): line = [] for j in xrange (size**2): line.append(answer.board[i][j]) question.append(line) visited = [] for i in xrange (size**2): visited.append([0] * size**2) counter = 0 level = size**4 while counter < size**4: i = random.randrange(size**2) j = random.randrange(size**2) if visited[i][j] == 0: counter += 1 visited[i][j] = 1 temp = question[i][j] question[i][j] = 0 level -= 1 solution = [] for k in xrange (size**2): solution.append(question[k][:]) solve = 0 for s in sudoku_solver.solve_sudoku((size, size), solution): solve += 1 if solve != 1: question[i][j] = temp level += 1 for i in xrange (size**2): print question[i] print "Number of fulled cells = ", level answer.show() return question, answer
def camera(): if request.environ.get('wsgi.websocket'): ws = request.environ['wsgi.websocket'] while True: cam = cv2.VideoCapture(0) success = False abort = False cells = [] while True: image = cam.read()[1] processed = process_frame(image) buffer = cv2.imencode('.jpg', processed)[1].tobytes() live_as_text = base64.b64encode(buffer).decode() ws.send('{"img":"' + str(live_as_text) + '"}') sleep(0.01) resp = ws.receive() py_resp = json.loads(resp) if (py_resp["aqc"]): cam.release() break #process image cv2.imwrite("debug.jpg", image) success, preImage, cells = Image_Pre_Processing(image) if (success): #then wait for another response from html preBuffer = cv2.imencode('.jpg', preImage)[1].tobytes() pre_as_text = base64.b64encode(preBuffer).decode() resp = ws.receive() py_resp = json.loads(resp) if (py_resp["waiting"]): ws.send('{"preImg":"' + str(pre_as_text) + '", "good_img": true}') abort = False else: ws.send('{"preImg":" ", "good_img": false}') abort = True else: resp = ws.receive() py_resp = json.loads(resp) ws.send('{"preImg":" ", "good_img": false}') abort = True if (success and not abort): for i, cell in enumerate(cells): cells[i] = cell / 255.0 sudoku_img = np.array(cells).reshape(-1, 32, 32, 1) ConvNet_pred = predict_ConvNet(model_ConvNet, sudoku_img) pred_labels = np.array([np.argmax(i) for i in ConvNet_pred]) prob_labels = np.around( np.array([np.max(i) for i in ConvNet_pred]), 3) conv_img = convert_sudoku_txt_to_image(pred_labels, PIL_bs_img, "FreeMono.ttf") open_cv_image = np.array(conv_img) convBuffer = cv2.imencode('.jpg', open_cv_image)[1].tobytes() conv_as_text = base64.b64encode(convBuffer).decode() resp = ws.receive() py_resp = json.loads(resp) if (py_resp["conv"]): ws.send('{"convImg": "' + str(conv_as_text) + '", "labels": [' + ', '.join( map(str, pred_labels.reshape(9, 9).T.flatten())) + '], "probs": [' + ', '.join( map(str, prob_labels.reshape(9, 9).T.flatten())) + '], "good_img": true}') abort = False else: ws.send( '{"convImg": " ", "labels": " ", "good_img": false}') abort = True elif (not abort): resp = ws.receive() py_resp = json.loads(resp) ws.send('{"convImg":" ", "labels": " ", "good_img": false}') abort = True if (not abort): resp = ws.receive() py_resp = json.loads(resp) if (py_resp["solve"]): ConvSolve_pred = predict_ConvSolve( model_ConvSolve, pred_labels.reshape(-1, 9, 9, 1).astype("float16")) solve_labels = np.array( [np.argmax(i) for i in ConvSolve_pred]) solve_probs = np.around( np.array([np.max(i) for i in ConvSolve_pred]), 3) solv_img = convert_sudoku_txt_to_image( solve_labels, PIL_bs_img, "FreeMono.ttf") open_cv_image_solve = np.array(solv_img) solvBuffer = cv2.imencode( '.jpg', open_cv_image_solve)[1].tobytes() solv_as_text = base64.b64encode(solvBuffer).decode() ws.send('{"solution": [' + ', '.join( map(str, solve_labels.reshape(9, 9).T.flatten())) + '], "probs": [' + ', '.join( map(str, solve_probs.reshape(9, 9).T.flatten())) + '], "solvImg": "' + str(solv_as_text) + '", "good_solve": true}') abort = False else: ws.send( '{"solution":" ", "solvImg": " ", "good_solve": false}' ) abort = True if (not abort): solution, algo_labels = solve_sudoku(pred_labels.reshape(9, 9)) if (solution): algo_img = convert_sudoku_txt_to_image( algo_labels.flatten(), PIL_bs_img, "FreeMono.ttf") open_cv_image_algo = np.array(algo_img) algoBuffer = cv2.imencode('.jpg', open_cv_image_algo)[1].tobytes() algo_as_text = base64.b64encode(algoBuffer).decode() resp = ws.receive() py_resp = json.loads(resp) if (py_resp["algo"]): ws.send('{"solution": [' + ', '.join( map(str, algo_labels.reshape(9, 9).T.flatten())) + '], "solvImg": "' + str(algo_as_text) + '", "good_solve": true}') abort = False else: ws.send( '{"solution":" ", "solvImg": " ", "good_solve": false}' ) abort = True
import operator import sudukoSolver import cv2 as cv import joblib import numpy as np import sudoku_solver import utils img = cv.imread('imgs/sudoku7.png') img = cv.resize(img, (700, 700)) orig_img = img.copy() # img = cv.pyrUp(img) dilated = utils.basic_preprocess(img) # Contours contours = utils.find_contours(dilated) img, crop_rect = utils.draw_corners(dilated, contours) img = utils.find_grid(img, crop_rect) digits, numbers_descriptors, squares = utils.extract_digits(img, False) cv.imshow('img before', img) cv.imwrite('polished.jpg', img) board = utils.create_board_knn(digits, squares) # print(board) board_copy = np.array(board, 'int').reshape(9, 9) print(board_copy) to_solve = np.zeros(img.shape) board, to_solve, res = sudoku_solver.solve_sudoku(board, to_solve) print(board) cv.imshow('img', to_solve) cv.waitKey(0)
from pathlib import Path import sudoku_solver import numpy as np f = open('../puzzles/hardsudoku-3.txt', 'r') lines = f.read() f.close() sudoku = [[character for character in line if not character == " "] for line in lines.split("\n")] def change_to_zero(sudoku): for r in range(9): for c in range(9): if sudoku[r][c] == "_": sudoku[r][c] = '0' sudoku[r] = list(map(int, sudoku[r])) return sudoku result = np.array(change_to_zero(sudoku)) print(result) sudoku_solver.solve_sudoku(result) print(result) print('Solved?: ', sudoku_solver.is_board_solved(result))
futures = [] if use_api: sudoku_pf, solved, exec_time = solve_sudoku_from_fields( sudoku, recognize_digit_ocr_space) else: sudoku_pf, solved, exec_time = solve_sudoku_from_fields( sudoku, recognize_digit_tesseract_ocr) print("Execution Time: " + str(exec_time)) correct, incorrect = evaluate_ocr(sudoku_pf) print("Evaluation: " + str(len(correct)) + ", " + str(len(incorrect))) #print("Correct: " + str(correct)) print("Incorrect:" + str(incorrect)) solve_sudoku(sudoku_pf) #image_intersects = draw_points(image, intersections) image_lines = draw_lines(image, h_lines) image_lines = draw_lines(image_lines, v_lines) """for i,j,_,_ in incorrect: imshow(str((i,j)), sudoku[i,j])""" # Some visualization of the (intermediate) results #imshow("Image Intersects", image_intersects) imshow("Image Lines", image_lines) key = waitKey(1) if (key == 27): break
def run(): config_path = r'configs/config_07' with open(config_path, 'r') as ymlfile: config = yaml.load(ymlfile, Loader=yaml.Loader) grid_finder = ContourGridFinder(config['grid_finder']) digit_classificator = HoughLineClassifier(config['digit_classifier']) cap = cv2.VideoCapture(0) output_img = None is_paused = False is_waiting_for_solution = False is_sollution_found = False while (True): if not is_paused: # Capture frame-by-frame _, frame = cap.read() try: solved_sudoku, input_sudoku = solve_sudoku( frame, grid_finder, digit_classificator) if solved_sudoku is None: print(">>> Sollution not found") solved_sudoku = input_sudoku else: if is_waiting_for_solution: is_sollution_found = True solved_sudoku.set_cropped_cell_bboxes( input_sudoku.cropped_cell_coordinates) solved_sudoku.set_transformation_matrix( input_sudoku.transformation_matrix) output_img = solved_sudoku.draw_full_result(frame) except: output_img = frame if is_waiting_for_solution and is_sollution_found: print(f'INPUT SUDOKU:\n{input_sudoku}\n\n') print(f'SOLVED SUDOKU:\n{solved_sudoku}\n') cv2.imshow('camera stream', solved_sudoku.draw_cropped_result()) cv2.waitKey(0) break else: cv2.imshow('camera stream', output_img) pressed_key = cv2.waitKey(1) if pressed_key & 0xFF == ord('q'): # Q - QUIT break elif pressed_key & 0xFF == ord('f'): # P - PAUSE is_paused = True elif pressed_key & 0xFF == ord('r'): # R - RETURN is_paused = False elif pressed_key & 0xFF == ord('p'): # P - PRINT is_waiting_for_solution = True else: continue # When everything done, release the capture cap.release() cv2.destroyAllWindows()
#cv2.putText(image, str(x_coord)+":"+str(y_coord), (x,y), font, 1, (0,0,0), 1, cv2.LINE_AA) # fill empty spaces with 0 for r in rows: for c in cols: key = r+c if not key in sudoku: sudoku[key] = str(0) else: original_positions.append(r+c) # matrix to string detected_sudoku_string = ss.generate_string_from_sudoku(sudoku) # solving sudoku solved_sudoku = ss.solve_sudoku(detected_sudoku_string) # has sudoku solution? if solved_sudoku == False: print("Not Solvable") sys.exit(0) # printing solution to img font = cv2.FONT_HERSHEY_DUPLEX for x in range(0, 9): for y in range(0, 9): row = rows[y] col = cols[x] if row+col in original_positions: continue pos_x = x*inner_rect_width+15
] if len(selected_imgs) == 81: for i in range(0, 9): l = selected_imgs[9 * i:9 * i + 9] l.sort(key=lambda x: x[1]) smatrix.append(l) for i in range(0, 9): for j in range(0, 9): img = smatrix[j][i][2] h, w = img.shape[:2] img = cv2.resize(img, (3 * w, 3 * h), interpolation=cv2.INTER_CUBIC) ret, img = cv2.threshold(img, 80, 255, cv2.THRESH_BINARY) digit = get_digit(img) if digit is not None: su[i][j] = digit print "Sudoku is:" ss.show(su) sol = ss.solve_sudoku(su) print "Solution is:" ss.show(sol) # cv2.imshow('image', image) # cv2.waitKey(0)
def solve(self, frame): """ :param frame: OpenCV image (3D numpy array (rows, columns, color channels)). It has to be either an BGR or a grayscale image. Otherwise an error may occur or the function won't find any board. :return: A copy of a frame with some modifications - vertices of the biggest quadrangle and solution if any is found. """ if frame is None: return frame frame = deepcopy(frame) warp_sudoku_board, warp_matrix = get_biggest_quadrangle(frame) if warp_sudoku_board is None: return frame boxes = get_boxes(warp_sudoku_board) digits_occurrence = check_digits_occurrence(boxes) inputs = prepare_inputs(boxes, digits_occurrence) if inputs is None: return frame # try to solve a sudoku in every rotation (0, 90, 180 and 270 degrees) current_attempt = 1 while current_attempt <= 4: rotation_angle = self.last_solved_sudoku_rotation + 90 * ( current_attempt - 1) rotated_inputs = rotate_inputs(inputs, rotation_angle) predictions = self.model.predict([rotated_inputs]) if not probabilities_are_good(predictions): current_attempt += 1 continue digits_grid = get_digits_grid(predictions, digits_occurrence, rotation_angle) if self.new_sudoku_solution_may_be_last_solution(digits_grid): self.last_solved_sudoku_rotation = rotation_angle result = inverse_warp_digits_on_frame( digits_grid, self.last_sudoku_solution, frame, warp_sudoku_board.shape, warp_matrix, rotation_angle) return result solved_digits_grid = sudoku_solver.solve_sudoku(digits_grid) if solved_digits_grid is None: current_attempt += 1 continue self.last_sudoku_solution = solved_digits_grid self.last_solved_sudoku_rotation = rotation_angle result = inverse_warp_digits_on_frame(digits_grid, solved_digits_grid, frame, warp_sudoku_board.shape, warp_matrix, rotation_angle) return result return frame
import yaml import numpy as np from sudoku_solver import solve_sudoku example = yaml.safe_load(open('example.yml', 'r'))['sudoku'] result, solution = solve_sudoku(np.array(example)) if result: print(solution)
rows = np.repeat(np.arange(1, 10), 9) cols = np.tile(np.arange(1, 10), 9) values = [] for line in input_data.split("\n"): if not "-" in line: vals = re.findall("[0-9]", line.rstrip()) values += [int(x) for x in vals] if len(rows) == len(cols) == len(values): known_cells = pd.DataFrame({"i": rows, "j": cols, "k": values}) board = known_cells.copy() known_cells = known_cells[known_cells["k"] != 0] board.k = ["" if x == 0 else str(x) for x in board.k] board = board.pivot(index="i", columns="j", values="k") if st.button("Solve!"): st.markdown("**Solution**") res = solve_sudoku(known_cells) st.write(board_matrix_to_dataframe(res)) else: st.markdown("**Board layout**") st.write(board) else: st.write( "Something is wrong with the layout of the board. Please try again.")