Python-opencv+KNN求解数独
最近一直在玩数独,突发奇想实现图像识别求解数独,输入到输出平均需要0.5s。
整体思路大概就是识别出图中数字生成list,然后求解。
输入输出demo
数独采用的是微软自带的Microsoft sudoku软件随便截取的图像,如下图所示:
经过程序求解后,得到的结果如下图所示:
程序具体流程
程序整体流程如下图所示:
读入图像后,根据求解轮廓信息找到数字所在位置,以及不包含数字的空白位置,提取数字信息通过KNN识别,识别出数字;无数字信息的在list中置0;生成未求解数独list,之后求解数独,将信息在原图中显示出来。
# -*-coding:utf-8-*-
import os
import cv2 as cv
import numpy as np
import time
####################################################
#寻找数字生成list
def find_dig_(img, train_set):
if img is None:
print("无效的图片!")
os._exit(0)
return
_, thre = cv.threshold(img, 230, 250, cv.THRESH_BINARY_INV)
_, contours, hierarchy = cv.findContours(thre, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
sudoku_list = []
boxes = []
for i in range(len(hierarchy[0])):
if hierarchy[0][i][3] == 0: # 表示父轮廓为 0
boxes.append(hierarchy[0][i])
# 提取数字
nm = []
for j in range(len(boxes)): # 此处len(boxes)=81
if boxes[j][2] != -1:
x, y, w, h = cv.boundingRect(contours[boxes[j][2]])
nm.append([x, y, w, h])
# 在原图中框选各个数字
cropped = img[y:y + h, x:x + w]
im = img_pre(cropped)#预处理
<