opencv3+python3.5成语填字游戏(一)印刷体汉字的分割
生活随笔
收集整理的這篇文章主要介紹了
opencv3+python3.5成语填字游戏(一)印刷体汉字的分割
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ?首先這是一個成語填字游戲,大概就是一張成語填字游戲圖片,通過opencv圖像識別后轉為矩陣,再通過解算法,解出答案,在顯示到圖片上。
? ?源代碼:https://github.com/mayue801/crossword-puzzle--idiom
? ?本文采用投影分割法對印刷體漢字進行分割。
? ?投影分割是先水平方向投影,在豎直方向投影,或者先豎直方向再水平方向投影。本文選用先豎直,再水平。
? ?1.豎直投影。
?------------
----------------
代碼:
#針對的是印刷版的漢字,所以采用了投影法分割 #此函數是行分割,結果是一行文字 def YShadow(path):img = cv2.imread(path) #原圖像gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #灰度圖像height,width = img.shape[:2]#blur = cv2.GaussianBlur(gray,(5,5),0) #高斯模糊blur = cv2.blur(gray,(8,8)) #均值模糊thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2) #自適應閾值分割temp = threshif(width > 500 and height > 400): #圖像字體較小時,需要進行膨脹操作kernel = np.ones((5,5),np.uint8) #卷積核dilation = cv2.dilate(thresh,kernel,iterations = 1) #膨脹操作使得單個文字圖像被黑像素填充temp = dilation'''cv2.imshow('image',temp)cv2.waitKey(0)cv2.destroyAllWindows()'''perPixelValue = 1 #每個像素的值projectValArry = np.zeros(width, np.int8) #創建一個用于儲存每列黑色像素個數的數組for i in range(0,height):for j in range(0,width):perPixelValue = temp[i,j]if (perPixelValue == 255): #如果是黑字,對應位置的值+1projectValArry[i] += 1# print(projectValArry[i])canvas = np.zeros((height,width), dtype="uint8")for i in range(0,height):for j in range(0,width):perPixelValue = 255 #白色背景canvas[i, j] = perPixelValuefor i in range(0,height):for j in range(0,projectValArry[i]):perPixelValue = 0 #黑色直方圖投影canvas[i, width-j-1] = perPixelValue'''cv2.imshow('canvas',canvas)cv2.waitKey(0)cv2.destroyAllWindows()'''list = []startIndex = 0 #記錄進入字符區的索引 endIndex = 0 #記錄進入空白區域的索引 inBlock = 0 #是否遍歷到了字符區內 for i in range(height):if (inBlock == 0 and projectValArry[i] != 0): #進入字符區inBlock = 1 startIndex = ielif (inBlock == 1 and projectValArry[i] == 0):#進入空白區endIndex = iinBlock = 0subImg = gray[startIndex:endIndex+1,0:width] #將對應字的圖片截取下來#print(startIndex,endIndex+1)list.append(subImg)#添加這個字圖像到list#print(len(list))return list? ?2.水平投影?------------------------
------------------
? ?分割完后,將對應圖片樣本存儲到對應文件夾,每個字共10種樣本
? ?將這些樣本及標記保存后,分別加載到samples.npy, label.npy中。供后續的機器學習算法訓練使用。
? ?下篇講解填字圖片漢字的提取與機器學習算法訓練樣本,識別漢字的過程。
總結
以上是生活随笔為你收集整理的opencv3+python3.5成语填字游戏(一)印刷体汉字的分割的全部內容,希望文章能夠幫你解決所遇到的問題。