微信咨询

微信咨询

13610*910*9

服务热线 7*24小时

电话咨询

Pyqt5+designer实现图片转文字桌面小软件

iamdu2020-01-26 12:30:40 浏览: 78232

主程序

import requests,json,os,time,datetime,sys
from aip import AipOcr 
import webbrowser
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import QtWidgets,QtGui
from PyQt5.QtCore import * 
import Ui_image4
from functools import partial
import requests
from bs4 import BeautifulSoup

class fileDialogdemo(QWidget):
    def __init__(self,parent=None):
        super(fileDialogdemo, self).__init__(parent)

    def picfile(self,ui):
        # filepath = 'F:\\2.jpg'
        # ui.textEdit_2.setText(filepath)

        #从C盘打开文件格式(*.jpg *.gif *.png *.jpeg)文件,返回路径
        image_file,_=QFileDialog.getOpenFileName(self,'Open file','/','Image files (*.jpg *.gif *.png *.jpeg)')
        print(image_file)
        ui.textEdit_2.setText(image_file)
        #设置标签的图片
        ui.label.setPixmap(QPixmap(image_file))
        '''
        在QFIleDialog.getOpenFileName()函数中 
        第一个参数self:用于指定父组件 
        第二个参数‘open file’:是QFileDialog对话框的标题 
        第三个参数‘C:\’默认打开的目录,‘.’代表程序运行的目录,‘/’代表当前盘下的根目录(window.linux系统),需要注意的是不同路径的显示方式,比如window平台下的C盘“C:\”等 
        第四个参数是对话框中文件扩展名过滤器(fliter),比如使用’Image files (.jpg .gif .png .jpeg)’表示只能显示扩展名为.jpg,.gif等文件

        '''

#提示信息
#这里是消息提示弹出框的主要代码
class MyWindow(QtWidgets.QWidget):  
    def __init__(self):  
        super().__init__()  
    #消息提示框
    def msg(self):  
        QMessageBox.information(self,"提示框","复制成功")
        # QMessageBox.question(self,"消息框标题","这是一条问答。")
        # QMessageBox.information(self,"消息框标题","这是一条消息。")
    def msg2(self):  
        QMessageBox.warning(self,"提示框","请上传图片")    

        
#点击广告图
def myclick(ui):
    webbrowser.open('http://www.baidu.com')
#复制内容
def copyText(ui):
    clipboard = QApplication.clipboard()
    word = ui.textEdit.toPlainText()
    clipboard.setText(word)
    # ui.textEdit.setTextBackgroundColor(QtGui.QColor(255,41,52))
    ui.textEdit.setStyleSheet('color:#1a75f2;background:#f2f5fc') #设置文字颜色
    # word.setStyleSheet('background:#1a75f2') #设置文字颜色
    myw = MyWindow()
    myw.msg()
    

def convert(ui):
        # 定义常量 
    APP_ID = '18093507'
    API_KEY = 'OeQ8jbtBOjbcYjgWyZtF3SPY'
    SECRET_KEY = '13x96WsNkr6TSOseWjtcjRO0nI0WsbkL'

    # 初始化AipFace对象 
    aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY) 

    # 读取图片 

    word = ui.textEdit_2.toPlainText()

    if word =='':
        myw = MyWindow()
        myw.msg2()
        return


    # print('图片地址是'+word)
    filePath = word

    def get_file_content(filePath): 
            with open(filePath, 'rb') as fp: 
                    return fp.read() 

    # 定义参数变量 
    options = { 
    'detect_direction': 'true', 
    'language_type': 'CHN_ENG', 
    } 

    # 调用通用文字识别接口 
    result = aipOcr.basicGeneral(get_file_content(filePath), options) 
    # print(json.dumps(result).encode('utf-8').decode("unicode-escape")) 
    res = json.dumps(result).encode('utf-8').decode("unicode-escape")

    # print(eval(res)['words_result'])
    # 通过eval函数转换成字典
    # for word in eval(res)['words_result']:
    # print(word['words'])
    # print(eval(res)['words_result'])
    try:
            #json字符串
            dic = json.dumps(eval(res)['words_result']).encode('utf-8').decode("unicode-escape")
            list1 = []
            #json.loads 将字符串转成字典格式
            for d in json.loads(dic):
                    list1.append(d['words'])
            result = '\r\n'.join(list1) #\r\n换行
            print(result)
            ui.textEdit.setText(result)
            # #结果写入记事本
            # tname = str(time.time()) #获取当前时间戳
            # txt = open('app/static/uploads/'+ tname +'.txt','w',encoding='utf-8')
            # txt.write(result) 
            # txt.close()

    except:
            print("转换失败,可能是图像内容太复杂或者不清晰,换个图试试吧")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = Ui_image4.Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    ex=fileDialogdemo()
    ui.pushButton_2.clicked.connect(partial(ex.picfile,ui))
    ui.pushButton.clicked.connect(partial(convert, ui))
    ui.graphicsView.mousePressEvent = myclick
    ui.pushButton_3.clicked.connect(partial(copyText,ui))
    sys.exit(app.exec_())





 

QTdesigner生成的UI文件 Ui_image4.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'f:\pydemo\Gui_Pyqt5\image4.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets
import requests

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(854, 645)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(40, 250, 171, 51))
        self.pushButton.setObjectName("pushButton")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(40, 320, 701, 201))
        self.textEdit.setObjectName("textEdit")
        self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView.setGeometry(QtCore.QRect(480, 50, 261, 131))
        self.graphicsView.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.graphicsView.setStyleSheet("border-image: url('F://pydemo//Gui_Pyqt5//ad.jpg')")
        self.graphicsView.setObjectName("graphicsView")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(40, 40, 75, 23))
        self.pushButton_2.setObjectName("pushButton_2")
        self.textEdit_2 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_2.setGeometry(QtCore.QRect(130, 40, 321, 31))
        self.textEdit_2.setObjectName("textEdit_2")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(40, 530, 75, 23))
        self.pushButton_3.setObjectName("pushButton_3")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(40, 90, 271, 141))
        # self.label.setPixmap(QtGui.QPixmap("https://img.alicdn.com/imgextra/i2/807175093/O1CN01ZQNxOo1nUdkIaPAqn_!!807175093.jpg"))
        #显示网络图片
        req = requests.get('https://img.alicdn.com/imgextra/i2/807175093/O1CN01ZQNxOo1nUdkIaPAqn_!!807175093.jpg')
        photo = QtGui.QPixmap()
        photo.loadFromData(req.content)
        self.label.setPixmap(photo)


        self.label.setText("")
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 854, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "图片转文字小工具"))
        self.pushButton.setText(_translate("MainWindow", "转换"))

        self.pushButton_2.setText(_translate("MainWindow", "浏览图片"))
        self.pushButton_3.setText(_translate("MainWindow", "复制"))