基于Python的OCR文字識(shí)別程序

看到一段基于Python的OCR文字識(shí)別程序太防,記錄備查

import pytesseract
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import os
from sys import platform

class MYOCR(QWidget):
    def __init__(self):
        super(MYOCR, self).__init__()

        XSIZE, YSIZE= 1400, 850
        self.resize(XSIZE, YSIZE)
        self.setWindowTitle("OCR文字識(shí)別小工具(星未)")
        
        self.imageFile=""
        btn_open = QPushButton(self)
        btn_open.setText("打開圖片")
        btn_open.move(10, 10)
        btn_open.clicked.connect(self.openimage)
        
        self.language='chi_sim'
        self.choice_lang = '語(yǔ)言'
        self.choice_list_lang = ['簡(jiǎn)體漢語(yǔ)','繁體漢語(yǔ)', '英語(yǔ)','OSD多語(yǔ)言']
        self.combobox_lang = QComboBox(self)
        self.combobox_lang.move(100,10)
        self.combobox_lang.addItem(self.choice_lang)              # 4
        self.combobox_lang.addItems(self.choice_list_lang)        # 5
        self.combobox_lang.currentIndexChanged.connect(lambda: self.on_combobox_func(self.combobox_lang)) 

        
        self.configLabel=QLabel(self)
        self.configLabel.move(250, 10)
        self.configLabel.setFixedSize(100, 25)
        self.configLabel.setText('config:')
        
        configTip1="""-oem:\n
                   0  Legacy engine only. 
                   1  Neural nets LSTM engine only.
                   2  Legacy + LSTM engines.
                   3  Default, based on what is available.\n"""
        configTip2="""--psm:\n
         0    Orientation and script detection (OSD) only.
         1    Automatic page segmentation with OSD.
         2    Automatic page segmentation, but no OSD, or OCR. (not implemented)
         3    Fully automatic page segmentation, but no OSD. (Default)
         4    Assume a single column of text of variable sizes.
         5    Assume a single uniform block of vertically aligned text.
         6    Assume a single uniform block of text.
         7    Treat the image as a single text line.
         8    Treat the image as a single word.
         9    Treat the image as a single word in a circle.
        10    Treat the image as a single character.
        11    Sparse text. Find as much text as possible in no particular order.
        12    Sparse text with OSD.
        13    Raw line. Treat the image as a single text line,
              bypassing hacks that are Tesseract-specific."""
              
        configTip = configTip1 + configTip2
              
        self.defaulet_config=r'--oem 3 --psm 6' 
        self.configbox = QTextEdit(self)
        self.configbox.move(300, 10)
        self.configbox.setFixedSize(250, 25)
        self.configbox.setText(self.defaulet_config)
        self.configbox.setToolTip(configTip)
        self.custom_oem_psm_config = self.configbox.toPlainText()
        self.config=self.custom_oem_psm_config
        
        btn_ocr = QPushButton(self)
        btn_ocr.setText("開始識(shí)別")
        btn_ocr.move(570, 10)
        btn_ocr.clicked.connect(self.run_terseract)
         
        self.saveFilePath= os.path.abspath(os.getcwd())
        self.saveFile='text.txt'
        self.saveFileFull=""
        if platform == "linux" or platform == "linux2":
            self.saveFileFull= self.saveFilePath + "/" + self.saveFile
        elif platform == "darwin":
            # OS X
            self.saveFileFull=self.saveFilePath + "/" +self.saveFile
        elif platform == "win32":
            self.saveFileFull=self.saveFilePath + "\\" + self.saveFile
        btn_save = QPushButton(self)
        btn_save.setText("保存到文件:")
        btn_save.move( int(XSIZE/2.0)+5, 10)
        btn_save.clicked.connect(self.save_text_to_file)
        
        self.filebox = QTextEdit(self)
        self.filebox.move( int(XSIZE/2.0)+100, 10)
        self.filebox.setFixedSize(540, 25)
        self.filebox.setText(self.saveFile)
        
        ################################################################      
        ### 圖片  
        self.xsize=690
        self.ysize=800
        self.label = QLabel(self)
        self.label.setText(" ")
        self.label.move(10, 40)
        self.label.setFixedSize(self.xsize, self.ysize)
        self.label.setScaledContents(True)
        self.label.setStyleSheet("QLabel{background:white;}"
                                 "QLabel{color:rgb(255,255,255);}"
                                 )

        ### 文字
        self.textbox = QTextEdit(self)
        self.textbox.move(705, 40)
        self.textbox.setFixedSize(self.xsize, self.ysize)
    
    def on_combobox_func(self, combobox):      
                                                              # 8
        if combobox == self.combobox_lang:
            dir_lang = {'語(yǔ)言':'chi_sim','簡(jiǎn)體漢語(yǔ)':'chi_sim', '繁體漢語(yǔ)':'chi_tra', '英語(yǔ)':'eng', 'OSD多語(yǔ)言':'osd'}
            all_lang = pytesseract.get_languages(config='')  
            self.language=dir_lang[ combobox.currentText() ] 
            
        elif combobox == self.combobox_method:
            dir_method=[]
            self.lineedit.setFont(combobox.currentFont())
            
        else:
            pass
            #QMessageBox.information(self, 'ComboBox lang', '{}: {}'.format(combobox.currentIndex(), combobox.currentText()))
  
    def save_text_to_file(self):
        filename = self.filebox.toPlainText()
        with open(filename,'w') as f:
            ocr_text=self.textbox.toPlainText()
            f.write(ocr_text)
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText("文字已保存到 " + filename + " 中外莲!") 
        msg.exec_()
            
    def openimage(self):
        imgName, imgType = QFileDialog.getOpenFileName(self, "打開圖片", "", "*.png;;*.jpg;;All Files(*)")
        imagefile= QtGui.QPixmap(imgName).scaled(self.label.width(), self.label.height())
        self.label.setPixmap(imagefile)
        self.imageFile = imgName

    def run_terseract(self):
        self.custom_oem_psm_config = self.configbox.toPlainText()
        self.config=self.custom_oem_psm_config
        if self.language=='語(yǔ)言': 
            self.language='chi_sim'
        
        self.textbox.setText("<font color='red'> 設(shè)別中欣除,請(qǐng)稍后.\n"+ \
            self.language + "\n"+ \
            self.config + ".</font>")
              
        QApplication.processEvents() 
        
        XImage = self.imageFile
        xstring= pytesseract.image_to_string(XImage, lang=self.language, config=self.config)
        if self.language=='chi_sim' or self.language=='chi_tra':
            self.textbox.setText(xstring.replace(' ',''))
        else:
            self.textbox.setText(xstring)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    my = MYOCR()
    my.show()
    sys.exit(app.exec_())
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市潭袱,隨后出現(xiàn)的幾起案子柱嫌,更是在濱河造成了極大的恐慌,老刑警劉巖敌卓,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件慎式,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡趟径,警方通過(guò)查閱死者的電腦和手機(jī)瘪吏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)蜗巧,“玉大人掌眠,你說(shuō)我怎么就攤上這事∧灰伲” “怎么了蓝丙?”我有些...
    開封第一講書人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)望拖。 經(jīng)常有香客問我渺尘,道長(zhǎng),這世上最難降的妖魔是什么说敏? 我笑而不...
    開封第一講書人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任鸥跟,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘医咨。我一直安慰自己枫匾,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開白布拟淮。 她就那樣靜靜地躺著干茉,像睡著了一般。 火紅的嫁衣襯著肌膚如雪很泊。 梳的紋絲不亂的頭發(fā)上角虫,一...
    開封第一講書人閱讀 51,692評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音委造,去河邊找鬼上遥。 笑死,一個(gè)胖子當(dāng)著我的面吹牛争涌,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播辣恋,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼亮垫,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了伟骨?” 一聲冷哼從身側(cè)響起饮潦,我...
    開封第一講書人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎携狭,沒想到半個(gè)月后继蜡,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡逛腿,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年稀并,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片单默。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡碘举,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出搁廓,到底是詐尸還是另有隱情引颈,我是刑警寧澤,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布境蜕,位于F島的核電站蝙场,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏粱年。R本人自食惡果不足惜售滤,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望逼泣。 院中可真熱鬧趴泌,春花似錦舟舒、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至吉捶,卻和暖如春夺鲜,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背呐舔。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工币励, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人珊拼。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓食呻,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親澎现。 傳聞我的和親對(duì)象是個(gè)殘疾皇子仅胞,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容