paddlehub 使用笔记

227 阅读2分钟

www.paddlepaddle.org.cn/hubdetail?n…

python 环境

准备python3.8+环境,如 conda create --name paddle_env python=3.8 --channel https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/

安装paddle

pip install paddlepaddle -i https://mirror.baidu.com/pypi/simple

安装paddlehub

pip install paddlehub -i https://mirror.baidu.com/pypi/simple

下载模型

Usage: hub

Commands: clear Clear all cached data. config Configure PaddleHub. convert Convert model to PaddleHub-Module. download Download PaddlePaddle pretrained module files. help Show help for commands. install Install PaddleHub module. list Show help for commands. run Run the specific module. search Search PaddleHub pretrained model through model keywords. serving Start Module Serving or Bert Service for online predicting. show Show the information of PaddleHub module. uninstall Uninstall PaddleHub module. version Show PaddleHub's version.

hub install ch_pp-ocrv3==1.2.0

预测

hub run ch_pp-ocrv3 --input_path "./picture/001.png"

import paddlehub as hub
import cv2

ocr = hub.Module(name="ch_pp-ocrv3", enable_mkldnn=True)       # mkldnn加速仅在CPU下有效
result = ocr.recognize_text(images=[cv2.imread('/PATH/TO/IMAGE')])

# or
# result = ocr.recognize_text(paths=['/PATH/TO/IMAGE'])

api文档

hub.Module(name="ch_pp-ocrv3", enable_mkldnn=True) 

__init__(text_detector_module=None, enable_mkldnn=False)
构造用于文本检测的模块

text_detector_module(str): 文字检测PaddleHub Module名字,如设置为None,则默认使用ch_pp-ocrv3_det Module。其作用为检测图片当中的文本。
enable_mkldnn(bool): 是否开启mkldnn加速CPU计算。该参数仅在CPU运行下设置有效。默认为False。

def recognize_text(images=[],
                    paths=[],
                    use_gpu=False,
                    output_dir='ocr_result',
                    visualization=False,
                    box_thresh=0.6,
                    text_thresh=0.5,
                    angle_classification_thresh=0.9,
                    det_db_unclip_ratio=1.5)

预测API,检测输入图片中的所有中文文本的位置。

参数
paths (list[str]): 图片的路径;
images (list[numpy.ndarray]): 图片数据,ndarray.shape 为 [H, W, C],BGR格式;
use_gpu (bool): 是否使用 GPU;若使用GPU,请先设置CUDA_VISIBLE_DEVICES环境变量
box_thresh (float): 检测文本框置信度的阈值;
text_thresh (float): 识别中文文本置信度的阈值;
angle_classification_thresh(float): 文本角度分类置信度的阈值
visualization (bool): 是否将识别结果保存为图片文件;
output_dir (str): 图片的保存路径,默认设为 ocr_result;
det_db_unclip_ratio: 设置检测框的大小;

返回
res (list[dict]): 识别结果的列表,列表中每一个元素为 dict,各字段为:
data (list[dict]): 识别文本结果,列表中每一个元素为 dict,各字段为: 
    - text(str): 识别得到的文本 
    - confidence(float): 识别文本结果置信度 
    - text_box_position(list): 文本框在原图中的像素坐标,4*2的矩阵,依次表示文本框左下、右下、右上、左上顶点的坐标 
    如果无识别结果则data为[]
save_path (str, optional): 识别结果的保存路径,如不保存图片则save_path为''

服务部署: 部署一个目标检测的在线服务

启动PaddleHub Serving

hub serving start -m ch_pp-ocrv3

目标检测的服务化API的部署,默认端口号为8866

发送预测请求

import requests
import json
import cv2
import base64

def cv2_to_base64(image):
    data = cv2.imencode('.jpg', image)[1]
    return base64.b64encode(data.tostring()).decode('utf8')

# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/ch_pp-ocrv3"
r = requests.post(url=url, headers=headers, data=json.dumps(data))

# 打印预测结果
print(r.json()["results"])