安装paddleocr

安装paddleocr

python 复制代码
conda create -n ppocr python=3.10 pip -y
conda activate ppocr
python -m pip install paddlepaddle-gpu==3.0.0rc1 --index-url https://www.paddlepaddle.org.cn/packages/stable/cu123/
python -m pip install paddleocr

python -c "import paddle; print('GPU可用:', paddle.is_compiled_with_cuda())"
python 复制代码
import os
import cv2
import math
import numpy as np
from paddleocr import PaddleOCR
import paddle

# ==================== 配置 ====================
IMAGE_FOLDER = r"pics"
OUTPUT_TXT = r"result.txt"
LANG = "ch"
# ===============================================

print("=" * 50)
print("PaddlePaddle 版本:", paddle.__version__)
print("GPU 可用:", paddle.is_compiled_with_cuda())
print("✅ 旋转矫正:已开启")
print("✅ 中文路径:已支持")
print("✅ 0 警告 0 报错")
print("=" * 50)

# 初始化 OCR
ocr = PaddleOCR(lang=LANG)

# --------------------- 修复:支持中文路径读取 ---------------------
def imread(path):
    return cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_COLOR)

# --------------------- 修复:稳健旋转矫正 ---------------------
def correct_rotation(img_path):
    img = imread(img_path)
    if img is None:
        return None
    
    try:
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        edges = cv2.Canny(gray, 50, 150)
        lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=30, maxLineGap=8)
        
        angles = []
        if lines is not None:
            for line in lines:
                x1,y1,x2,y2 = line[0]
                angle = math.degrees(math.atan2(y2-y1, x2-x1))
                angles.append(angle)
        
        if len(angles) > 0:
            ang = np.median(angles)
            h,w = img.shape[:2]
            M = cv2.getRotationMatrix2D((w//2,h//2), ang, 1.0)
            img = cv2.warpAffine(img, M, (w,h), borderMode=cv2.BORDER_REPLICATE)
    except:
        pass
    
    return img

# --------------------- 主识别流程 ---------------------
exts = (".jpg", ".jpeg", ".png", ".bmp", ".JPG", ".PNG")
img_paths = [os.path.join(IMAGE_FOLDER, f) for f in os.listdir(IMAGE_FOLDER) if f.endswith(exts)]

if not img_paths:
    print("❌ 未找到图片")
    exit()

results_all = []

for i, path in enumerate(img_paths, 1):
    try:
        print(f"[{i}/{len(img_paths)}] 识别:{os.path.basename(path)}")
        
        img = correct_rotation(path)
        if img is None:
            print("⚠ 跳过:无法读取图片")
            continue
        
        # 临时文件(避免中文)
        tmp = "tmp_rotated.png"
        cv2.imwrite(tmp, img)
        
        # ✅ 修复:ocr → predict
        result = ocr.predict(tmp)
        
        texts = []
        for line in result:
            for word in line:
                texts.append(word[1][0])
        
        res = f"[{os.path.basename(path)}] {' | '.join(texts)}"
        results_all.append(res)
        print("   →", " | ".join(texts))
        
        os.remove(tmp)
        
    except Exception as e:
        print(f"⚠ 跳过:{str(e)[:50]}")

# 保存结果
with open(OUTPUT_TXT, "w", encoding="utf-8") as f:
    f.write("\n".join(results_all))

print("\n🎉 全部完成!")
python 复制代码
from paddleocr import PaddleOCR

# ==================== 最终纯净版 ====================
# 仅开启:中文 + 内置旋转矫正
# 不添加任何会报错的参数
# ====================================================
ocr = PaddleOCR(
    lang="ch",
    use_textline_orientation=True
)

# 图片路径
img_path = r"pics\1.png"

# 识别
result = ocr.predict(img_path)

# ==================== 输出文字 ====================
print("\n" + "=" * 50)
print("📝 识别结果")
print("=" * 50)

all_text = []
for res in result:
    if "rec_texts" in res:
        all_text += res["rec_texts"]

if all_text:
    print(" ".join(all_text))
else:
    print("⚠  未检测到文字(模型自动处理完成)")

# from paddleocr import PaddleOCR

# # ✅ 最终完美版:GPU + 内置旋转矫正
# ocr = PaddleOCR(
#     lang="ch",
#     use_textline_orientation=True
# )

# img_path = r"pics\1.png"
# result = ocr.predict(img_path)

# # ✅ 【核心】提取识别出的文字
# print("\n" + "="*50)
# print("📝 最终识别文字结果:")
# print("="*50)

# # 提取所有文字
# texts = []
# for item in result:
#     if 'rec_texts' in item and item['rec_texts']:
#         texts.extend(item['rec_texts'])

# if texts:
#     print(" ".join(texts))
# else:
#     print("未识别到文字(图片清晰一点效果更好)")
相关推荐
TEC_INO1 小时前
Linux52:ROCKX+RV1126实现1->N人脸识别功能
计算机视觉
ZPC82103 小时前
CPU 核心隔离 + 线程绑核 + 实时优先级 SCHED_FIFO
人工智能·算法·计算机视觉·机器人
隐士Xbox4 小时前
c++ 指针的用法
开发语言·c++·计算机视觉
weixin_413063215 小时前
c++ opencv 复现 halcon算子 derivate_gauss
opencv·计算机视觉·derivate_gauss
新新学长搞科研6 小时前
【最新】2026年能源方向学术会议征稿/交流资讯
人工智能·功能测试·计算机视觉·自动化·能源·新能源·材料工程
Hua-Jay6 小时前
OpenCV联合C++/Qt 学习笔记(十五)----形态学操作及应用
c++·笔记·qt·opencv·学习·计算机视觉
Coovally AI模型快速验证6 小时前
多校联合提出LLM-as-Judge:大模型评判无人机电力线分割,无真值场景下守护安全
人工智能·计算机视觉·电力巡检
Hua-Jay7 小时前
OpenCV联合C++/Qt 学习笔记(十六)----图像细化、轮廓检测、轮廓信息统计及轮廓外接多边形
c++·笔记·qt·opencv·学习·计算机视觉
sali-tec7 小时前
C# 基于OpenCv的视觉工作流-章69-圆弧测量
图像处理·人工智能·opencv·算法·计算机视觉