识别一张表格照片输出excle文件的具体代码
时间: 2023-04-03 07:05:13 浏览: 73
您好,以下是识别一张表格照片输出excel文件的具体代码:
import cv2
import numpy as np
import pytesseract
import pandas as pd
# 读取图片
img = cv2.imread('table.jpg')
# 灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# 获取轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 获取表格轮廓
table_contours = []
for i in range(len(contours)):
cnt = contours[i]
area = cv2.contourArea(cnt)
if area < 1000:
continue
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
w, h = rect[1]
if w / h > 5 or h / w > 5:
continue
table_contours.append(box)
# 绘制表格轮廓
cv2.drawContours(img, table_contours, -1, (0, 0, 255), 2)
# 识别表格内容
data = []
for i in range(len(table_contours)):
box = table_contours[i]
x, y, w, h = cv2.boundingRect(box)
roi = gray[y:y + h, x:x + w]
text = pytesseract.image_to_string(roi, lang='chi_sim')
rows = text.split('\n')
for row in rows:
cols = row.split('\t')
data.append(cols)
# 输出excel文件
df = pd.DataFrame(data)
df.to_excel('table.xlsx', index=False, header=False)
希望能对您有所帮助。
阅读全文