python识别ocr 图片和pdf文件

复制代码
#识别图片
pip3 install paddleocr
pip3 install paddlepaddle


#识别pdf
pip3 install PyMuPDF

重点:路径不能有中文,不然pdf文件访问不了

复制代码
from paddleocr import PaddleOCR
from rest_framework.response import Response
from rest_framework.views import APIView


# 识别单张图片
class GetOneImage(APIView):
    def get(self, request, *args, **kwargs):
        ocr = PaddleOCR(use_angle_cls=True, lang="ch")  # need to run only once to download and load model into memory
        img_path = 'F:/OCR/data/4.png'
        result = ocr.ocr(img_path, cls=True)
        for idx in range(len(result)):
            res = result[idx]
            for line in res:
                print(line)

        # 显示结果
        for idx in range(len(result)):
            res = result[idx]
            txts = [line[1][0] for line in res]
        return Response({'code': 200, "data": txts})


import datetime
import fitz  # fitz就是pip install PyMuPDF
import os
import cv2
from paddleocr import PPStructure
from paddleocr.ppstructure.recovery.recovery_to_doc import sorted_layout_boxes

# 中文测试图
table_engine = PPStructure(recovery=True, lang='ch')


#识别pdf
class GetPDF(APIView):
    def get(self, request, *args, **kwargs):
        pdfPath = "F:/OCR/image/13.pdf";
        imagePath = "F:/OCR/image/13"
        startTime_pdf2img = datetime.datetime.now()  # 开始时间
        print("imagePath=" + imagePath)
        if not os.path.exists(imagePath):
            os.makedirs(imagePath)
        pdfDoc = fitz.open(pdfPath)
        totalPage = pdfDoc.page_count
        for pg in range(totalPage):
            page = pdfDoc[pg]
            rotate = int(0)
            zoom_x = 2
            zoom_y = 2
            mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
            pix = page.get_pixmap(matrix=mat, alpha=False)
            print(f'正在保存{pdfPath}的第{pg + 1}页,共{totalPage}页')
            pix.save(imagePath + '/' + f'images_{pg + 1}.png')
        endTime_pdf2img = datetime.datetime.now()
        print(f'{pdfDoc}-pdf2img-花费时间={(endTime_pdf2img - startTime_pdf2img).seconds}秒')
        img_path = imagePath;
        text = []
        imgs = os.listdir(img_path)
        for img_name in imgs:
            img = cv2.imread(os.path.join(img_path, img_name))
            result = table_engine(img)
            h, w, _ = img.shape
            res = sorted_layout_boxes(result, w)
            for line in res:
                line.pop('img')
                print(line)
                for pra in line['res']:
                    text.append(pra['text'])
                text.append('\n')
        return Response({'code': 200, "data": text})

参考:使用paddleOCR批量识别pdf_paddleocr pdf-CSDN博客

相关推荐
Nicole-----3 分钟前
Python - Union联合类型注解
开发语言·python
Eric.5653 小时前
python advance -----object-oriented
python
云天徽上3 小时前
【数据可视化-107】2025年1-7月全国出口总额Top 10省市数据分析:用Python和Pyecharts打造炫酷可视化大屏
开发语言·python·信息可视化·数据挖掘·数据分析·pyecharts
THMAIL3 小时前
机器学习从入门到精通 - 数据预处理实战秘籍:清洗、转换与特征工程入门
人工智能·python·算法·机器学习·数据挖掘·逻辑回归
@HNUSTer4 小时前
Python数据可视化科技图表绘制系列教程(六)
python·数据可视化·科技论文·专业制图·科研图表
THMAIL4 小时前
深度学习从入门到精通 - AutoML与神经网络搜索(NAS):自动化模型设计未来
人工智能·python·深度学习·神经网络·算法·机器学习·逻辑回归
山烛5 小时前
深度学习:残差网络ResNet与迁移学习
人工智能·python·深度学习·残差网络·resnet·迁移学习
eleqi5 小时前
Python+DRVT 从外部调用 Revit:批量创建梁(2)
python·系统集成·revit·自动化生产流水线·外部访问
BYSJMG5 小时前
计算机毕设大数据方向:基于Spark+Hadoop的餐饮外卖平台数据分析系统【源码+文档+调试】
大数据·hadoop·分布式·python·spark·django·课程设计
OC溥哥9996 小时前
Flask论坛与个人中心页面开发教程完整详细版
后端·python·flask·html