ubuntu OCR 脚本

1. 百度 PaddleOCR 介绍

2. 环境安装

shell 复制代码
pip install paddlepaddle -i https://pypi.tuna.tsinghua.edu.cn/simple
# 进入 https://github.com/PaddlePaddle/PaddleOCR 
# 这里有个 requirements.txt
pip install paddleocr -i https://mirror.baidu.com/pypi/simple
pip install -r requirements.txt -i https://mirror.baidu.com/pypi/simple

3. 用法: my_ocr.py 图片或文件夹

python 复制代码
#!/bin/env python
import os
import sys
import time
import logging                    # 关闭WARNING
from tqdm.auto import trange      # 进度条
from paddleocr import PaddleOCR   # 百度识别

logging.disable(logging.DEBUG)    # 关闭DEBUG日志的打印
logging.disable(logging.WARNING)  # 关闭WARNING日志的打印

file = "out.txt"

def ocr_imgs(img):
    result = ocr.ocr(img, cls=False)
    if len(result[0]) == 0:
        result = ocr.ocr(img, cls=False, det=False)
    with open(file, 'a') as f:
        f.write(f'\n{img.center(50, "-")}\n')
        for idx in range(len(result)):
            res = result[idx]
            for line in res:
                if isinstance(line, list):
                    f.write(f'{line[-1][0]}\n')
                elif isinstance(line, tuple):
                    f.write(f'{line[0]}\n')
        # f.flush()

def check_args():
    if len(sys.argv) < 2:
        print("Usage: %s <path> or <path/file>" % sys.argv[0])
        exit()

    arg = sys.argv[1]
    if os.path.isfile(arg):
        arg = os.path.dirname(arg)
        single_file = True
    elif os.path.isdir(arg):
        single_file = False
    
    os.chdir(arg)
    os.remove(file) if os.path.exists(file) else False
    return single_file

########################################################################
if __name__ == "__main__":
    print(f"[{time.strftime('%X')}] 识别开始...")
    start = time.time()
    imagelist = [os.path.basename(sys.argv[1])] if check_args() else list(filter(os.path.isfile, os.listdir()))
    imagelist.sort(key=str.lower)
    ocr = PaddleOCR(use_angle_cls=False, lang="ch")  # use_angle_cls 竖文字
    for i in trange(len(imagelist),leave=False):
        image = imagelist[i]
        fn, ex = os.path.splitext(image)
        if ex in ['.jpg', '.jpeg', '.png']:  # bmp/webp/tiff/svg/gif
            ocr_imgs(image)

    end = time.time()
    run_time = round(end - start)
    print(f"[{time.strftime('%X')}] 结束耗时{run_time}秒")

    cmd="gedit " + file + "&"
    os.system(cmd)
相关推荐
94621931zyn68 小时前
关于应用 - Cordova 与 OpenHarmony 混合开发实战
笔记·python
知远同学13 小时前
Anaconda的安装使用(为python管理虚拟环境)
开发语言·python
Blossom.11814 小时前
AI编译器实战:从零手写算子融合与自动调度系统
人工智能·python·深度学习·机器学习·flask·transformer·tornado
半壶清水14 小时前
开源免费的在线考试系统online-exam-system部署方法
运维·ubuntu·docker·开源
热爱专研AI的学妹14 小时前
数眼搜索API与博查技术特性深度对比:实时性与数据完整性的核心差异
大数据·开发语言·数据库·人工智能·python
Mr_Chenph15 小时前
Miniconda3在Windows11上和本地Python共生
开发语言·python·miniconda3
智航GIS17 小时前
5.1 if语句基础
开发语言·python
华研前沿标杆游学17 小时前
2026年湖南省工业旅游线路
python
APIshop17 小时前
深入解析京东API接口:如何高效获取商品详情与SKU信息
python
94621931zyn617 小时前
备份恢复 - Cordova 与 OpenHarmony 混合开发实战
python