Python 语言 用 Pytesseract 从截图中提取表格 转 Excel 可编辑格式 + 自动调整列宽

Python阿木 发布于 1 天前 3 次阅读


阿木博主一句话概括:使用Pytesseract从截图中提取表格并转换为Excel可编辑格式

阿木博主为你简单介绍:
本文将介绍如何使用Python语言和Pytesseract库从截图中提取表格,并将其转换为Excel可编辑格式。我们将详细讲解整个流程,包括图像预处理、表格识别、表格转换以及自动调整列宽等步骤。

一、
随着信息技术的不断发展,表格在数据展示和存储中扮演着重要角色。手动从图片中提取表格并转换为可编辑格式是一项繁琐的工作。本文将介绍如何利用Python语言和Pytesseract库,实现从截图中提取表格并转换为Excel可编辑格式,从而提高工作效率。

二、环境搭建
1. 安装Python:从Python官网下载并安装Python,推荐使用Python 3.6及以上版本。
2. 安装Pytesseract:在命令行中执行以下命令安装Pytesseract:

pip install pytesseract

3. 安装Tesseract OCR:从Tesseract OCR官网下载并安装适用于您操作系统的版本。

三、代码实现
1. 导入所需库
python
from PIL import Image
import pytesseract
import pandas as pd
import openpyxl
from openpyxl.utils import get_column_letter

2. 图像预处理
python
def preprocess_image(image_path):
打开图像
image = Image.open(image_path)
转换为灰度图像
gray_image = image.convert('L')
应用阈值处理
threshold_image = gray_image.point(lambda p: p > 128 and 255)
return threshold_image

3. 表格识别
python
def extract_table(image_path):
预处理图像
preprocessed_image = preprocess_image(image_path)
使用Pytesseract识别表格
table_data = pytesseract.image_to_data(preprocessed_image, output_type=pytesseract.Output.DICT)
return table_data

4. 表格转换
python
def table_to_excel(table_data, excel_path):
创建Excel工作簿
workbook = openpyxl.Workbook()
sheet = workbook.active
遍历表格数据
for i, row in enumerate(table_data['text']):
for j, cell in enumerate(row):
将单元格数据写入Excel
sheet.cell(row=i+1, column=j+1, value=cell)
保存Excel文件
workbook.save(excel_path)

5. 自动调整列宽
python
def adjust_column_width(excel_path):
打开Excel文件
workbook = openpyxl.load_workbook(excel_path)
sheet = workbook.active
遍历所有列
for column in sheet.columns:
max_length = 0
column = [cell.value for cell in column]
找到最大长度
max_length = max(len(str(cell)) if cell is not None else 0 for cell in column)
调整列宽
adjusted_width = (max_length + 2)
sheet.column_dimensions[get_column_letter(column[0].column)].width = adjusted_width
保存Excel文件
workbook.save(excel_path)

6. 主函数
python
def main():
image_path = 'input_image.jpg' 输入图片路径
excel_path = 'output_table.xlsx' 输出Excel文件路径
提取表格
table_data = extract_table(image_path)
转换为Excel
table_to_excel(table_data, excel_path)
自动调整列宽
adjust_column_width(excel_path)
print("表格已成功提取并转换为Excel格式。")

if __name__ == '__main__':
main()

四、总结
本文介绍了如何使用Python语言和Pytesseract库从截图中提取表格,并将其转换为Excel可编辑格式。通过图像预处理、表格识别、表格转换以及自动调整列宽等步骤,实现了从图片到Excel的高效转换。在实际应用中,可以根据需求对代码进行优化和扩展。