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)
相关推荐
im_AMBER1 小时前
学习日志05 python
python·学习
大虫小呓1 小时前
Python 处理 Excel 数据 pandas 和 openpyxl 哪家强?
python·pandas
BD_Marathon1 小时前
Ubuntu:Mysql服务器
服务器·mysql·ubuntu
哪 吒1 小时前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
摸爬滚打李上进2 小时前
重生学AI第十六集:线性层nn.Linear
人工智能·pytorch·python·神经网络·机器学习
0wioiw03 小时前
Ubuntu基础(监控重启和查找程序)
linux·服务器·ubuntu
Tipriest_3 小时前
Ubuntu常用的软件格式deb, rpm, dmg, AppImage等打包及使用方法
linux·运维·ubuntu
GBXLUO3 小时前
windows的vscode无法通过ssh连接ubuntu的解决办法
vscode·ubuntu
凛铄linshuo4 小时前
爬虫简单实操2——以贴吧为例爬取“某吧”前10页的网页代码
爬虫·python·学习
牛客企业服务4 小时前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘