位置: IT常识 - 正文

Table Transformer做表格检测和识别实践(clh锅)

编辑:rootadmin
Table Transformer做表格检测和识别实践

推荐整理分享Table Transformer做表格检测和识别实践(clh锅),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:clh锅,ambition锅,锅具 wmf,锅mini,wmm锅,sentruth锅,sentruth锅,sentruth锅,内容如对您有帮助,希望把文章链接给更多的朋友!

计算机视觉方面的三大顶级会议:ICCV,CVPR,ECCV.统称ICE CVPR 2022文档图像分析与识别相关论文26篇汇集简介

论文: PubTables-1M: Towards comprehensive table extraction from unstructured documents是发表于CVPR上的一篇论文 作者发布了两个模型,表格检测和表格结构识别。

论文讲解可以参考【论文阅读】PubTables- 1M: Towards comprehensive table extraction from unstructured documents

hugging face Table Transformer 使用文档 hugging face Table DETR 使用文档

检测表格from huggingface_hub import hf_hub_downloadfrom transformers import AutoImageProcessor, TableTransformerForObjectDetectionimport torchfrom PIL import Imagefile_path = hf_hub_download(repo_id="nielsr/example-pdf", repo_type="dataset", filename="example_pdf.png")image = Image.open(file_path).convert("RGB")image_processor = AutoImageProcessor.from_pretrained("microsoft/table-transformer-detection")model = TableTransformerForObjectDetection.from_pretrained("microsoft/table-transformer-detection")inputs = image_processor(images=image, return_tensors="pt")outputs = model(**inputs)# convert outputs (bounding boxes and class logits) to COCO APItarget_sizes = torch.tensor([image.size[::-1]])results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[ 0]for score, label, box in zip(results["scores"], results["labels"], results["boxes"]): box = [round(i, 2) for i in box.tolist()] print( f"Detected {model.config.id2label[label.item()]} with confidence " f"{round(score.item(), 3)} at location {box}" ) region = image.crop(box) #检测 region.save('xxx.jpg') #保存# Detected table with confidence 1.0 at location [202.1, 210.59, 1119.22, 385.09]

Table Transformer做表格检测和识别实践(clh锅)

结果 :效果不错

表格结构识别

参考:https://github.com/NielsRogge/Transformers-Tutorials/blob/master/Table%20Transformer/Using_Table_Transformer_for_table_detection_and_table_structure_recognition.ipynb

import torchfrom PIL import Imagefrom transformers import DetrFeatureExtractorfrom transformers import AutoImageProcessor, TableTransformerForObjectDetectionfrom huggingface_hub import hf_hub_downloadfeature_extractor = DetrFeatureExtractor()file_path = hf_hub_download(repo_id="nielsr/example-pdf", repo_type="dataset", filename="example_pdf.png")image = Image.open(file_path).convert("RGB")encoding = feature_extractor(image, return_tensors="pt")model = TableTransformerForObjectDetection.from_pretrained("microsoft/table-transformer-structure-recognition")with torch.no_grad(): outputs = model(**encoding)target_sizes = [image.size[::-1]]results = feature_extractor.post_process_object_detection(outputs, threshold=0.6, target_sizes=target_sizes)[0]# plot_results(image, results['scores'], results['labels'], results['boxes'])results

获取列图像:

columns_box_list = [results['boxes'][i].tolist() for i in range(len(results['boxes'])) if results['labels'][i].item()==1]columns_1 = image.crop(columns_box_list[0]) columns_1.save('columns_1.jpg') #保存

可视化:import matplotlib.pyplot as plt# colors for visualizationCOLORS = [[0.000, 0.447, 0.741], [0.850, 0.325, 0.098], [0.929, 0.694, 0.125], [0.494, 0.184, 0.556], [0.466, 0.674, 0.188], [0.301, 0.745, 0.933]]def plot_results(pil_img, scores, labels, boxes): plt.figure(figsize=(16, 10)) plt.imshow(pil_img) ax = plt.gca() colors = COLORS * 100 for score, label, (xmin, ymin, xmax, ymax), c in zip(scores.tolist(), labels.tolist(), boxes.tolist(), colors): ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=c, linewidth=3)) text = f'{model.config.id2label[label]}: {score:0.2f}' ax.text(xmin, ymin, text, fontsize=15, bbox=dict(facecolor='yellow', alpha=0.5)) plt.axis('off') plt.show()post_process_object_detection方法:

OpenCV PIL图像格式互转

参考:https://blog.csdn.net/dcrmg/article/details/78147219

PIL–》OpenCV

cv2.cvtColor(numpy.asarray(image),cv2.COLOR_RGB2BGR)import cv2from PIL import Imageimport numpyimage = Image.open("plane.jpg")image.show()img = cv2.cvtColor(numpy.asarray(image),cv2.COLOR_RGB2BGR)cv2.imshow("OpenCV",img)cv2.waitKey()

OpenCV --》 PIL

Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))import cv2from PIL import Imageimport numpyimg = cv2.imread("plane.jpg")cv2.imshow("OpenCV",img)image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))image.show()cv2.waitKey()

综上,模型检测列代码如下

# 检测模型import cv2from huggingface_hub import hf_hub_downloadfrom transformers import AutoImageProcessor, TableTransformerForObjectDetectionimport torchfrom PIL import Imageimport torchfrom PIL import Imagefrom transformers import DetrFeatureExtractorfrom transformers import AutoImageProcessor, TableTransformerForObjectDetectionfrom huggingface_hub import hf_hub_downloadimport numpy as npimport matplotlib.pyplot as pltimport cv2def dectect_table(file_path): # file_path = hf_hub_download(repo_id="nielsr/example-pdf", repo_type="dataset", filename="example_pdf.png") image = Image.open(file_path).convert("RGB") # transformers.AutoImageProcessor 是一个通用图像处理器 image_processor = AutoImageProcessor.from_pretrained("microsoft/table-transformer-detection") model = TableTransformerForObjectDetection.from_pretrained("microsoft/table-transformer-detection") inputs = image_processor(images=image, return_tensors="pt") outputs = model(**inputs) # convert outputs (bounding boxes and class logits) to COCO API target_sizes = torch.tensor([image.size[::-1]]) results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[ 0 ] box_list = [] for score, label, box in zip(results["scores"], results["labels"], results["boxes"]): box = [round(i, 2) for i in box.tolist()] print( f"Detected {model.config.id2label[label.item()]} with confidence " f"{round(score.item(), 3)} at location {box}" ) box_list.append(box) region = image.crop(box) #检测 # region.save('xxx.jpg') #保存 return region#def plot_results(pil_img, scores, labels, boxes): # colors for visualization COLORS = [[0.000, 0.447, 0.741], [0.850, 0.325, 0.098], [0.929, 0.694, 0.125], [0.494, 0.184, 0.556], [0.466, 0.674, 0.188], [0.301, 0.745, 0.933]] plt.figure(figsize=(16, 10)) plt.imshow(pil_img) ax = plt.gca() colors = COLORS * 100 for score, label, (xmin, ymin, xmax, ymax), c in zip(scores.tolist(), labels.tolist(), boxes.tolist(), colors): if label == 1: ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=c, linewidth=3)) # text = f'{model.config.id2label[label]}: {score:0.2f}' text = f'{score:0.2f}' ax.text(xmin, ymin, text, fontsize=15, bbox=dict(facecolor='yellow', alpha=0.5)) plt.axis('off') plt.show()def cv_show(img): ''' 展示图片 @param img: @param name: @return: ''' cv2.namedWindow('name', cv2.WINDOW_KEEPRATIO) # cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO cv2.imshow('name', img) cv2.waitKey(0) cv2.destroyAllWindows()def dect_col(file_path): ''' 识别列 :param file_path: :return: ''' # example_table= region # width, height = image.size # image.resize((int(width * 0.5), int(height * 0.5))) table = dectect_table(file_path) # 截取左半边 feature_extractor = DetrFeatureExtractor() # file_path = hf_hub_download(repo_id="nielsr/example-pdf", repo_type="dataset", filename="example_table.png") # image = Image.open(file_path).convert("RGB") # image = cv2.imread(file_path) left_table = table.crop((0, 0, table.size[0]//2,table.size[1])) encoding = feature_extractor(left_table, return_tensors="pt") model = TableTransformerForObjectDetection.from_pretrained("microsoft/table-transformer-structure-recognition") with torch.no_grad(): outputs = model(**encoding) target_sizes = [left_table.size[::-1]] results = feature_extractor.post_process_object_detection(outputs, threshold=0.6, target_sizes=target_sizes)[0] plot_results(left_table, results['scores'], results['labels'], results['boxes']) # columns_box_list = [results['boxes'][i].tolist() for i in range(len(results['boxes'])) if results['labels'][i].item()==1] # columns_box_list.sort() # columns_1 = left_table.crop(columns_box_list[0]) # left, upper, right, lower # columns_1.save('columns_1.jpg') #保存 return columns_box_listdect_col(r'xxxx.jpg')
本文链接地址:https://www.jiuchutong.com/zhishi/295358.html 转载请保留说明!

上一篇:07---vue前端实现增删改查(vue.js前端)

下一篇:HTML学生个人网站作业设计:个人主页博客web网页设计制作 (HTML+CSS) (1)(学生个人网页制作html5)

  • 基本保险包括
  • 印花税的分录如何做
  • 附加税申报表里怎么填写
  • 工业企业取得土地使用权专用发票可以抵扣吗?
  • 出口免税收入的计税依据
  • 计提房产税会计分录怎么做
  • 二手车没有发票能过户吗
  • 建筑行业小规模纳税人免税政策
  • 小规模纳税人差额计税情形
  • 机票行程单丢了可以重新打吗
  • 非本公司员工如何申报个税
  • 商场采用联营方式的原因
  • 发票冲红增值税怎么申报
  • 长期借款转入实收资本
  • 承包给对方了,受伤了要赔偿吗
  • 出售二手车税收优惠
  • 增值税小规模纳税人的税率
  • 小微企业销售已按固定资产入账的办公家具也享受免税政策吗?
  • 开发项目未竣工前土地使用税怎么缴纳
  • 固定资产折旧转入什么科目
  • 收取对方损失赔偿
  • 哪些科目适用于借方多栏式
  • 无法访问移动网络怎么办
  • 公司废业
  • 认缴出资额日期没有是什么意思
  • php二维码生成代码
  • 政府搬迁补偿款不够建房怎么办
  • abstract php
  • .exe是指什么文件
  • php接口规则
  • 入固定资产含税吗
  • 会计学中借和贷怎么区分
  • php中实现文件上传需要用到哪几个函数
  • thinkphp,onethink和thinkox中验证码不显示的解决方法分析
  • sql数据库语句基本语法
  • win11的截屏
  • 杀疯了出自哪里
  • js-cookie vue
  • php抢红包功能思路
  • bad block bitmap checksum
  • 新手为什么要买二手车
  • 印花税申报时间填错了怎么处理?
  • 会计核算方法有几种
  • 电梯销售公司利润
  • 增值税附加税有哪几种
  • dedecms仿站如何做
  • php cms
  • python local
  • 房地产材料采购清单
  • 备用金用发票核销去哪核销
  • 企业收到赠送商品会计分录
  • 长期股权投资与其他权益工具投资的区别
  • 个体工商户怎么注册
  • 所得税弥补以前年度亏损是几年
  • 电商平台返佣金个人税点
  • 劳务派遣的公司值得去吗
  • 成本价和原价一样吗
  • 私对公可以转账怎么转
  • 私人企业会计工作内容
  • 存储过程 decode
  • centos rpm安装方法
  • vista windows
  • linux怎么禁用防火墙
  • iis支持什么后端语言
  • centos 拷贝
  • mac怎么多开
  • windowsxp怎么用
  • c盘里面放什么
  • windowsxp的设置在哪
  • linux文本操作命令
  • jquery中如何获取元素?
  • Unity for Absolute Beginners(一)
  • unity5.x游戏开发指南
  • 深入理解新发展理念
  • python中的文件
  • flask框架官方文档
  • python函数详解
  • 税务局副局长分管业务
  • 发票与报销内容不一样
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设