基于paddleOCR实现文字提取

138 阅读1分钟

安装依赖

pip install paddlepaddle
pip install paddleocr
pip install requests
pip install numpy matplotlib opencv-python

代码展示

from paddleocr import PaddleOCR, draw_ocr
import cv2
from matplotlib import pyplot as plt
import numpy as np

# 初始化 OCR 模型
ocr = PaddleOCR(use_angle_cls=True, lang='ch')  # 'ch' 代表简体中文,其他语言可以使用 'en' 等

# 读取图像
image_path = './test.png'
# 使用 Unicode 解码路径
image_path = image_path.encode('utf-8').decode('utf-8')
image = cv2.imread(image_path)

# 调试输出:检查图像数据类型
print(f"Image type: {type(image)}")

# 确保图像是 NumPy 数组
image = np.array(image)
print(f"NumPy array type: {image.dtype}")

# 执行 OCR 识别
result = ocr.ocr(image_path, cls=True)

# 打印识别结果
for line in result:
    print(1)
    print(line)
    
# 调试输出:检查识别结果的格式
print(f"Result: {result}")

# 分离识别结果中的各个部分
# boxes: 文本区域的坐标,确保转换为整数
# txts: 识别出的文本
# scores: 识别的置信度得分
boxes = [np.int0(np.array(elements[0])) for elements in result[0]]

# 检查座标格式和数据
for box in boxes:
    print(f"Box: {box} \nType: {type(box)}\nData Type: {box.dtype}")
    
# 提取文字部分
txts = [elements[1][0] for elements in result[0]]
# 提取可信度部分
scores = [elements[1][1] for elements in result[0]]

# 将识别结果绘制在图像上
im_show = draw_ocr(image, boxes, txts, scores, font_path='C:/Windows/Fonts/simsun.ttc')

# 显示结果
plt.imshow(im_show)
plt.axis('off')
plt.show()