Python圖文識別技術【入門必學】

Python圖文識別技術分享
使用 tesseract-ORC 識別文字,識別率不算過高,須要自我訓練 tessdata 數據,才能更精確的識別你想要讓電腦認識出來的文字!
ps:另外不少人在學習Python的過程當中,每每由於遇問題解決不了從而致使本身放棄,爲此我建了個Python全棧開發交流.裙 :一久武其而而流一思(數字的諧音)轉換下能夠找到了,裏面有最新Python教程項目可拿,不懂的問題有老司機解決哦,一塊兒相互監督共同進步

接下來看代碼:python

import os import pytesseract from PIL import Image from collections import defaultdict #pip install pytesseract #pip install pillow # tesseract.exe所在的文件路徑 pytesseract.pytesseract.tesseract_cmd = 'C://Program Files (x86)/Tesseract-OCR/tesseract.exe' # 獲取圖片中像素點數量最多的像素 def get_threshold(image): pixel_dict = defaultdict(int) # 像素及該像素出現次數的字典 rows, cols = image.size for i in range(rows): for j in range(cols): pixel = image.getpixel((i, j)) pixel_dict[pixel] += 1 count_max = max(pixel_dict.values()) # 獲取像素出現出多的次數 pixel_dict_reverse = {v: k for k, v in pixel_dict.items()} threshold = pixel_dict_reverse[count_max] # 獲取出現次數最多的像素點 return threshold # 按照閾值進行二值化處理 # threshold: 像素閾值 def get_bin_table(threshold): # 獲取灰度轉二值的映射table table = [] for i in range(256): rate = 0.1 # 在threshold的適當範圍內進行處理 if threshold * (1 - rate) <= i <= threshold * (1 + rate): table.append(1) else: table.append(0) return table # 去掉二值化處理後的圖片中的噪聲點 def cut_noise(image): rows, cols = image.size # 圖片的寬度和高度 change_pos = [] # 記錄噪聲點位置 # 遍歷圖片中的每一個點,除掉邊緣 for i in range(1, rows - 1): for j in range(1, cols - 1): # pixel_set用來記錄該店附近的黑色像素的數量 pixel_set = [] # 取該點的鄰域爲以該點爲中心的九宮格 for m in range(i - 1, i + 2): for n in range(j - 1, j + 2): if image.getpixel((m, n)) != 1: # 1爲白色,0位黑色 pixel_set.append(image.getpixel((m, n))) # 若是該位置的九宮內的黑色數量小於等於4,則判斷爲噪聲 if len(pixel_set) <= 4: change_pos.append((i, j)) # 對相應位置進行像素修改,將噪聲處的像素置爲1(白色) for pos in change_pos: image.putpixel(pos, 1) return image # 返回修改後的圖片 # 識別圖片中的數字加字母 # 傳入參數爲圖片路徑,返回結果爲:識別結果 def OCR_lmj(img_path): image = Image.open(img_path) # 打開圖片文件 imgry = image.convert('L') # 轉化爲灰度圖 # 獲取圖片中的出現次數最多的像素,即爲該圖片的背景 max_pixel = get_threshold(imgry) # 將圖片進行二值化處理 table = get_bin_table(threshold=max_pixel) out = imgry.point(table, '1') # 去掉圖片中的噪聲(孤立點) out = cut_noise(out) # 保存圖片 # out.save('E://figures/img_gray.jpg') # 僅識別圖片中的數字 # text = pytesseract.image_to_string(out, config='digits') # 識別圖片中的數字和字母 text = pytesseract.image_to_string(out) # 去掉識別結果中的特殊字符 exclude_char_list = ' .:\\|\'\"?![],()~@#$%^&*_+-={};<>/¥' text = ''.join([x for x in text if x not in exclude_char_list]) # print(text) return text def main(): # 識別指定文件目錄下的圖片 # 圖片存放目錄figures dir = 'D:\\ProjectSVN\\ChuanShengGuoJi\\trunk\CSGJ\\image2' # 遍歷figures下的png,jpg文件 for file in os.listdir(dir): if file.endswith('.png') or file.endswith('.jpg'): image_path = '%s/%s' % (dir, file) # 圖片路徑 answer = file.split('.')[0] # 圖片名稱,即圖片中的正確文字 recognizition = OCR_lmj(image_path) # 圖片識別的文字結果 print((answer, recognizition)) main()

以上就是分享的代碼,都明白了沒?另外不少人在學習Python的過程當中,每每由於遇問題解決不了從而致使本身放棄,爲此我建了個Python全棧開發交流.裙 :一久武其而而流一思(數字的諧音)轉換下能夠找到了,裏面有最新Python教程項目可拿,不懂的問題有老司機解決哦,一塊兒相互監督共同進步git

本文的文字及圖片來源於網絡加上本身的想法,僅供學習、交流使用,不具備任何商業用途,版權歸原做者全部,若有問題請及時聯繫咱們以做處理。markdown

相關文章
相關標籤/搜索