opencv3+python3.5成语填字游戏(二)填字图片汉字

2018-05-22  本文已影响0人  mler801

GitHub源代码

上一篇说的是汉字的分割。今天该实际填字图片的解析了。实际图片如下:

image
## 轮廓提取
image, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
  1. 提取100个方格的代码;
for i in range(len(hierarchy[0])):
    if hierarchy[0][i][3] == 0:
        boxes.append(hierarchy[0][i])
        indexs.append(i)
  1. 提取方格中的数字,还有将白色空白方格填'1',黄色方格填“0”,主要是为了形成初始填字矩阵,便于后续的解密算法的进行。代码:
#提取方格中的汉字
for j in range(len(boxes)):
    if boxes[j][2] == -1: #方格中空白
        x,y,w,h = cv2.boundingRect(contours[indexs[j]])
        number_boxes.append([x,y,w,h])
        #cv2.rectangle(img,(x-1,y-1),(x+w-10,y+h-10),(0,0,255),1)
        centerColor = img[round((2*y+h)/2),round((2*x+w)/2)]
        #print(centerColor)
        if(centerColor[0] > 200): #区分出黄色格与白色格,黄色(0,255,255)白色(255,255,255)
            #print(y/box_h,round(y/box_h),x/box_w,round(x/box_w))
            miyu[round(y/box_h)][round(x/box_w)] = "1" #白色空格填‘1’
    elif boxes[j][2] != -1: #方格中有字
        x,y,w,h = cv2.boundingRect(contours[boxes[j][2]])
        #print(x,y,w,h)

        number_boxes.append([x,y,w,h])
        #cv2.rectangle(img,(x-1,y-1),(x+w+1,y+h+1),(0,255,0),1)
        #img = cv2.drawContours(img, contours, boxes[j][2], (0,255,0), 1)
        ## 对提取的数字进行处理
        number_roi = gray[y:y+h, x:x+w]
        ## 统一大小
        resized_roi=cv2.resize(number_roi,(30,30))
        thresh1 = cv2.adaptiveThreshold(resized_roi,255,1,1,11,2) 
        ## 归一化像素值
        normalized_roi = thresh1/255.  
        '''
        cv2.imshow("thresh1", thresh1)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        '''
        ## 展开成一行让knn识别
        sample1 = normalized_roi.reshape((1,len(normalized_roi)*len(normalized_roi[0])))
        sample1 = np.array(sample1,np.float32)
        
        ## knn识别
        retval, results, neigh_resp, dists = model.findNearest(sample1, 1)        
        number = int(results.ravel()[0])
        #print(number)
        #numbers.append(number)
     
        # 第一个参数为打印的坐标,第二个为打印的文本,第三个为字体颜色,第四个为字体
        draw.text((x+(w/2)+10,y-10), str(hanzis[number-1]), (0, 0, 255), font=font) 
        
        ## 求在矩阵中的位置
        miyu[round(y/box_h)][round(x/box_w)] = str(hanzis[number-1])
  1. 图片中汉字的识别,使用的是knn算法,代码:
#创建knn对象并训练样本
model = cv2.ml.KNearest_create()
model.train(samples,cv2.ml.ROW_SAMPLE,labels)
## knn识别
retval, results, neigh_resp, dists = model.findNearest(sample1, 1)   #预测测试样本     
number = int(results.ravel()[0]) #得出预测样本的样本标记
上一篇下一篇

猜你喜欢

热点阅读