识别发票信息写入excel的python代码
时间: 2023-07-23 14:18:46 浏览: 61
以下是一个简单的Python代码示例,用于从发票图像中提取信息并将其写入Excel表格中:
``` python
import cv2
import pytesseract
import pandas as pd
# 读取发票图像
img = cv2.imread("invoice.png")
# 转换成灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 对图像进行二值化处理
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# 使用Tesseract OCR提取文本
text = pytesseract.image_to_string(thresh, lang='chi_sim')
# 将文本转换成列表格式
lines = text.split('\n')
# 创建一个空的DataFrame,用于存储发票信息
df = pd.DataFrame(columns=['发票号码', '开票日期', '购买方名称', '购买方税号', '销售方名称', '销售方税号', '商品名称', '金额'])
# 遍历每一行文本,提取信息并添加到DataFrame中
for line in lines:
if '发票代码' in line:
invoice_code = line.split(':')[1].strip()
if '发票号码' in line:
invoice_number = line.split(':')[1].strip()
if '开票日期' in line:
invoice_date = line.split(':')[1].strip()
if '购买方名称' in line:
buyer_name = line.split(':')[1].strip()
if '购买方纳税人识别号' in line:
buyer_tax_id = line.split(':')[1].strip()
if '销售方名称' in line:
seller_name = line.split(':')[1].strip()
if '销售方纳税人识别号' in line:
seller_tax_id = line.split(':')[1].strip()
if '商品名称' in line:
item_name = line.split(' ')[1].strip()
item_amount = line.split(' ')[2].strip()
# 将商品名称和金额添加到DataFrame中
df = df.append({'发票号码': invoice_number, '开票日期': invoice_date, '购买方名称': buyer_name, '购买方税号': buyer_tax_id, '销售方名称': seller_name, '销售方税号': seller_tax_id, '商品名称': item_name, '金额': item_amount}, ignore_index=True)
# 将DataFrame写入Excel文件
df.to_excel('invoice_info.xlsx', index=False)
```
此代码使用以下Python库:
- OpenCV:用于图像处理和文本提取。
- pytesseract:用于OCR(光学字符识别)将文本从图像中提取出来。
- pandas:用于创建和写入Excel文件。
请注意,这只是一个简单的示例,需要根据您的具体情况进行修改和调整。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)