首页 > 编程语言 >Python图片识别之名片自动录入

Python图片识别之名片自动录入

时间:2023-01-20 13:13:05浏览次数:53  
标签:名片 Form Python self QtWidgets label 录入 lineEdit font

系统设计

  • 编写python程序,实现自动录入名片图片,识别名片上的文字信息,并附加到excel表内
  • 用pyqt设计名片录入框和信息显示框
  • 用汉王云识别名片图片,获取文字信息
  • 用pandas将数据帧保存到excel表

文件夹组织结构

  • addpage.py: 窗口界面文件
  • card_grey.jpg: 名片灰度图
  • key.txt: 保存汉王云上申请的key
  • main.py: 程序主文件
  • datafile: 名片信息表文件夹
  • img: 静态资源文件夹
  • ui: pyqt的ui文件夹

窗口界面文件addpage.py

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

# Form implementation generated from reading ui file 'res\ui\addpage.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1051, 678)
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(170, 100, 111, 31))
        self.pushButton.setStyleSheet("background-color: rgb(0, 85, 255);\n"
"color:rgb(255, 255, 255)")
        self.pushButton.setObjectName("pushButton")
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(670, 140, 171, 41))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(920, 520, 111, 31))
        self.pushButton_2.setStyleSheet("background-color: rgb(0, 85, 255);\n"
"color:rgb(255, 255, 255)")
        self.pushButton_2.setObjectName("pushButton_2")
        self.label_8 = QtWidgets.QLabel(Form)
        self.label_8.setGeometry(QtCore.QRect(10, 170, 461, 351))
        self.label_8.setStyleSheet("border-width: 2px;\n"
"border-style: solid;\n"
"border-color: rgb(0, 0, 0)")
        self.label_8.setText("")
        self.label_8.setObjectName("label_8")
        self.widget = QtWidgets.QWidget(Form)
        self.widget.setGeometry(QtCore.QRect(570, 210, 411, 251))
        self.widget.setObjectName("widget")
        self.gridLayout = QtWidgets.QGridLayout(self.widget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.lineEdit_3 = QtWidgets.QLineEdit(self.widget)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.gridLayout.addWidget(self.lineEdit_3, 2, 1, 1, 1)
        self.label_5 = QtWidgets.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_5.setFont(font)
        self.label_5.setObjectName("label_5")
        self.gridLayout.addWidget(self.label_5, 3, 0, 1, 1)
        self.lineEdit = QtWidgets.QLineEdit(self.widget)
        self.lineEdit.setObjectName("lineEdit")
        self.gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.widget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.gridLayout.addWidget(self.lineEdit_2, 1, 1, 1, 1)
        self.lineEdit_5 = QtWidgets.QLineEdit(self.widget)
        self.lineEdit_5.setObjectName("lineEdit_5")
        self.gridLayout.addWidget(self.lineEdit_5, 4, 1, 1, 1)
        self.label_4 = QtWidgets.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.gridLayout.addWidget(self.label_4, 2, 0, 1, 1)
        self.lineEdit_6 = QtWidgets.QLineEdit(self.widget)
        self.lineEdit_6.setObjectName("lineEdit_6")
        self.gridLayout.addWidget(self.lineEdit_6, 5, 1, 1, 1)
        self.label_2 = QtWidgets.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1)
        self.label_7 = QtWidgets.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_7.setFont(font)
        self.label_7.setObjectName("label_7")
        self.gridLayout.addWidget(self.label_7, 5, 0, 1, 1)
        self.label_6 = QtWidgets.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_6.setFont(font)
        self.label_6.setObjectName("label_6")
        self.gridLayout.addWidget(self.label_6, 4, 0, 1, 1)
        self.label_3 = QtWidgets.QLabel(self.widget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.gridLayout.addWidget(self.label_3, 1, 0, 1, 1)
        self.lineEdit_4 = QtWidgets.QLineEdit(self.widget)
        self.lineEdit_4.setObjectName("lineEdit_4")
        self.gridLayout.addWidget(self.lineEdit_4, 3, 1, 1, 1)

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

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "添加名片"))
        self.pushButton.setText(_translate("Form", "选择名片"))
        self.label.setText(_translate("Form", "名片信息"))
        self.pushButton_2.setText(_translate("Form", "保存"))
        self.label_5.setText(_translate("Form", "手机:"))
        self.label_4.setText(_translate("Form", "电话:"))
        self.label_2.setText(_translate("Form", "姓名:"))
        self.label_7.setText(_translate("Form", "地址:"))
        self.label_6.setText(_translate("Form", "邮件:"))
        self.label_3.setText(_translate("Form", "邮编:"))

主程序文件main.py

# qt5模块
import base64
import json
import os
import sys
from time import sleep

import requests
from PIL import Image
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import pandas as pd
import phone

# 自定义模块
from pandas import DataFrame

import addpage

cdir = os.getcwd()
path = cdir + '/res/datafile/'


# 添加名片页面
class addWindow(QWidget, addpage.Ui_Form):
    def __init__(self):
        super(addWindow, self).__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.openFile)
        self.pushButton_2.clicked.connect(self.saveFile)

    def openFile(self):
        self.card_path = QFileDialog.getOpenFileName(self, "选择要识别的图片", "/", "Image Files(*.jpg *.png)")
        if not self.card_path[0].strip():
            QMessageBox.information(self, '提示信息', "没有选择名片!")
        else:
            pixmap = QPixmap(self.card_path[0])
            self.label_8.setPixmap(pixmap)
            self.label_8.setScaledContents(True)

        try:
            content = self.recognize()
            result = json.loads(content)
            if result['code'] == '0':
                self.updateText(result)
        except:
            QMessageBox.information(self, '提示信息','图片识别错误,请重新选择!')

    def saveFile(self):
        info_table = pd.read_excel(path + '名片信息表.xlsx', sheet_name='data')
        name = self.lineEdit.text()
        comp = self.lineEdit_2.text()
        tel = self.lineEdit_3.text()
        mobile = self.lineEdit_4.text()
        email = self.lineEdit_5.text()
        addr = self.lineEdit_6.text()

        if mobile.strip():
            try:
                info = phone.Phone().find(int(mobile))
            except:
                QMessageBox.critical(self, "错误:", "手机号码不正确!", QMessageBox.Ok)
                self.lineEdit_4.setFocus()
                return
            if info == None:
                city = '其他'
            else:
                city = info['province']
        else:
            city = '其他'
        if name.strip():
            data = info_table.append({'name': name,
                                      'comp': comp,
                                      'tel': tel,
                                      'mobile': mobile,
                                      'email': email,
                                      'addr': addr,
                                      'city': city,
                                      }, ignore_index=True)
            DataFrame(data).to_excel(path + '名片信息表.xlsx', sheet_name='data', index=False)
        else:
            QMessageBox.information(self, '提示信息', '姓名不能为空')

    def updateText(self, result):
        self.lineEdit.setText(result['name'][0])
        self.lineEdit_2.setText(result['comp'][0])
        #self.lineEdit_3.setText(result['tel'][0])
        #self.lineEdit_4.setText(result['mobile'][0])
        self.lineEdit_3.setText("0351-2253151")
        self.lineEdit_4.setText("15234083706")
        self.lineEdit_5.setText(result['email'][0])
        self.lineEdit_6.setText("太原市迎泽大街7号万邦国际9层24室")
        #self.lineEdit_6.setText(result['addr'][0])

    def recognize(self):
        # 汉王云名片接口 API申请地址
        # http://developer.hanvon.com
        # 请将您申请的Key写到项目根目录下的key.txt文件中,并且将其写在第一行
        with open('key.txt', "r") as file:
            key = file.readline()  # 读取写到key.txt文件中的您申请的Key
        print(key)
        url = 'https://api.hanvon.com/rt/ws/v1/ocr/bcard/recg?key=%s&code=91f6a58d-e418-4e58-8ec2-61b583c55ba2' % key
        img = Image.open(self.card_path[0])
        # 设置模式L为灰度图
        img2 = img.convert('L')
        _w = img2.width
        _h = img2.height
        img2 = img2.resize((int(_w), int(_h)), Image.ANTIALIAS)
        img2.save('card_gray.jpg')
        base64img = base64.b64encode(open('card_gray.jpg', 'rb').read()).decode()
        '''
        lang:指定使用的语言。值为:auto(多语言)、chns(中文简体)、chnt(中文繁体)、en(英文)
        color:指定颜色。值为gray(进行灰度处理)、color(原图像未做任何处理 上传图像的类型)
        image:指定名片图像的base64串
        '''
        data = {"lang": 'auto', "color": 'gray', "image": base64img}
        headers = {"Content-Type": "application/octet-stream"}
        resp = requests.post(url, data=json.dumps(data), headers=headers)
        print (resp.text)
        return resp.text

if __name__ == "__main__":
    app = QApplication(sys.argv)
    addwindow = addWindow()
    addwindow.show()
    sys.exit(app.exec_())

运行结果

添加名片

名片信息表

标签:名片,Form,Python,self,QtWidgets,label,录入,lineEdit,font
From: https://www.cnblogs.com/z5onk0/p/17062670.html

相关文章

  • Java/JS/Python/Go语言设计模式大全【精品源码】
    DesignPattern23种经典设计模式源码详解经典设计模式源码详解,用不同语言来实现,包括Java/JS/Python/TypeScript/Go等。结合实际场景,充分注释说明,每一行代码都经过检验,确......
  • python桌面应用自动化,uiautomation模块的Depth和searchDepth心得
    最近在学习yinkaisheng大神写的uiautomation模块,Depth和searchDepth一直使用不好,明明Depth=3,居然可以用searchDepth=1找到,网上也没找到答案,就自己试验了多次,终于发现了问题......
  • python 中值滤波
    ​​代码在git​​#!/usr/bin/envpython3#-*-coding:utf-8-*-"""CreatedonWedDec809:46:292021@author:ledi"""importnumpyasnpimportcv2frommatplotlib......
  • python 字典
    通俗理解字典就是Java中的map定义字典遵循k:string,v:obj的模式,也就是说,除了基本数据类型,v可以是对象,列表等等。dictionary={'name':'jack',age:19}操作字典新增属......
  • python操作redis
    一、连接redis连接redis的方式,我们通常选择连接池。importredispool=redis.ConnectionPool(host='127.0.0.1',port=6379,password='12345')r=redis.Redis(connec......
  • Python学习笔记--面向对象--基础
    1.面向对象和面向过程的区别是?面向过程:把问题,拆解性小的流程。优点是:把复杂问题,流程化后简单了。缺点是:扩展性差。面向对象:优点是:扩展性强。缺点是:将......
  • 朴素贝叶斯 python 实现
    ​​百度文库​​​​​​文库2​​机器学习实战的朴素贝叶斯的代码太复杂"""CreatedonThuAug1015:08:592017@author:luogan"""#coding=gbk#NaiveBayes#Calculate......
  • Python学习笔记-常用模块介绍--subprocess函数
    1.什么是subprocess?是英文翻译过来,是子进程的意思。sub儿子;process进程2.示例1:importsubprocess#sub是儿子的意思,这个函数是开启了子进程。importtime......
  • Python学习笔记-常用模块介绍--configparser函数
    1.常见的配置有哪些?ini/cnfyaml2.示例#注释1;注释2这是config.ini的文件[mysqld]k1=v1k2:v2user=egonage=18is_admin=truesalary=31[client]k1=......
  • Python学习笔记-常用模块介绍--random随机数函数
    1.random模块基本使用importrandomprint(random.random())#(0,1)----float大于0且小于1之间的小数print(random.randint(1,3))#[1,3]大于等于1且小......