zoukankan      html  css  js  c++  java
  • 百度ocr文字识别接口使用

    最近有个需求需要识别图片中的文字,所以就用到了百度的ocr接口,结果在测试的过程中被图片格式搞的有点晕,试了好久终于成功了,在此记录一下。

    附ocr接口文档地址:https://cloud.baidu.com/doc/OCR/OCR-API.html#.E8.BF.94.E5.9B.9E.E8.AF.B4.E6.98.8E
    

    我们先来看一下接口说明:

    这里我们主要来看图片参数,图片参数可以通过两种方式传递:

    1. url方式

    通过url传递比较简单,直接拿过来用就好,实例代码如下:

    <?php
    function request_post($url = '', $param = '', $header = []) {
        if (empty($url) || empty($param)) {
            return false;
        }   
    
        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($curl);//运行curl
        curl_close($curl);
    
        return $data;
    }
    
    $api = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=xxxxxxx';
    $image_url = 'xxx.com/a.png'; // 网络图片url
    $header = ['Content-Length: application/x-www-form-urlencoded'];
    $post = [ 
        'url' => $image_url,
    ];
    
    $res = request_post($api, $post, $header);
    

    2、image方式

    image参数需要对本地图片进行base64编码,然后进行传递,接口文档中比较坑的点:

    • Content-Type用的是multipart/form-data
    • base64编码后并不需要进行urlencode
    $api = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=xxxxxxx';
    $header = ['Content-Length: multipart/form-data'];
    
    $file = '/data/image/a.png'; // 本地图片路径
    $image = base64_encode(file_get_contents($file));
    $post = [ 
        'image' => $image,
    ];
    
    $res = request_post($api, $post, $header);
    
  • 相关阅读:
    Unity 移动端的复制这么写
    Unity如何管理住Android 6.0 调皮的权限
    谷歌商店Apk下载器
    Unity编辑器下重启
    git pull error
    如何简单的实现新手引导之UGUI篇
    linux系统安装python3.5
    Grafana设置mysql为数据源
    hyper -v 虚拟机(win_server)忘记密码重置
    zabbix报错:the information displayed may not be current
  • 原文地址:https://www.cnblogs.com/chenguoli/p/8520888.html
Copyright © 2011-2022 走看看