当前位置:   article > 正文

服务器搭建OCR文字识别流程 + 本地调用方式_hub serving ocr-system 启动后接口文档

hub serving ocr-system 启动后接口文档

1.下载安装包
wget https://www.python.org/ftp/python/3.8.8/Python-3.8.8.tgz
2.下载python3的编译依赖包
yum install -y gcc patch libffi-devel python-devel  zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel
3.创建python目录
mkdir  /usr/python
4.解压安装包到目录下(安装包挪到上面创建的目录下)
tar -zxf Python-3.8.8.tgz
5.指定安装目录
cd /usr/python/Python-3.8.8
 ./configure --prefix=/usr/python/
6.编译
make
7.编译安装
make install
8.添加linux环境变量 (使用root账号?)
vi /etc/profile
#python
export PYTHON_HOME=安装路径
export PATH=$PYTHON_HOME/bin:$PATH
保存后  执行source /etc/profile
9.修改python的链接指向
mv /usr/bin/python /usr/bin/python.bak  
ln -s /usr/local/bin/python/Python-3.8.8/bin/python3 /usr/bin/python

10、安装PaddlePaddle Fluid V2.0 (下载失败就python -m pip install --upgrade pip 更新pip)
python3 -m pip install paddlepaddle==2.2.2 -i https://pypi.tuna.tsinghua.edu.cn/simple   
(如果提示pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
就先执行:yum install openssl-devel -y,然后./configure --prefix=/usr/python/然后make然后make install)

11.下载解压orc项目
wget https://github.com/PaddlePaddle/PaddleOCR/archive/develop.zip
unzip develop.zip # 解压

12.进入解压出来的目录下面,安装依赖库
 pip3 install -r requirements.txt   
13.安装paddlehub
  pip3 install paddlehub --upgrade -i https://pypi.tuna.tsinghua.edu.cn/simple

14.设置环境变量
 export PYTHONPATH=/usr/local/bin/python/PaddleOCR 11步骤的解压目录地址 (/../../PaddleOCR)
 
15.安装服务模块:(根据需要安装,主要是第三个安装成功就可以)

进入到PaddleOCR目录,执行命令
# 安装检测服务模块:  
hub install deploy/hubserving/ocr_det/
# 安装识别服务模块:  
hub install deploy/hubserving/ocr_rec/
# 安装检测+识别串联服务模块:
hub install deploy/hubserving/ocr_system/
//将inference文件夹放到PaddleOCR目录下


16.启动项目
hub serving start -c config.json
! hub serving start -m ocr_system
如果报错ImportError: libSM.so.6: cannot open shared object file: No such file or directory
yum whatprovides libSM.so.6 #查看版本改成对应的版本
就执行:yum install libSM-1.2.3-1.el8.x86_64 --setopt=protected_multilib=false

如果提示yum的python版本不对那么:
/usr/bin/yum和/usr/libexec/urlgrabber-ext-down文件修改第一行指定为python2.7
 
 
python PaddleOCR/tools/test_hubserving.py http://127.0.0.1:8868/predict/ocr_system /ocr/
 
 
 
 
 
 
 -------------windows
 E:
 cd PaddleOCR-develop
 conda activate paddle38
 hub serving start -m ocr_system

以下调用方式

    @PostMapping("/upload")
    public Object fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req){
        try {
            //接收上传文件
            //Receiving uploaded files
            String fileName = System.currentTimeMillis()+file.getOriginalFilename();
            String destFileName=req.getServletContext().getRealPath("")+"uploaded"+ File.separator+fileName;
            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            System.out.println(destFile);
            file.transferTo(destFile);
            //向前端模板引擎传入上传文件的地址
            //The address of the uploaded file is passed in to the front-end template engine
            //开始准备请求API
            //Start preparing the request API
            //创建请求头
            //Create request header
            HttpHeaders headers = new HttpHeaders();
            //设置请求头格式
            //Set the request header format
            headers.setContentType(MediaType.APPLICATION_JSON);
            //构建请求参数
            //Build request parameters
            MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
            //读入静态资源文件
            //Read the static resource file
            InputStream imagePath = new FileInputStream(destFile);
            //添加请求参数images,并将Base64编码的图片传入
            //Add the request parameter Images and pass in the Base64 encoded image
            map.add("images", ImageToBase64(imagePath));
            //构建请求
            //Build request
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
            HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
            httpRequestFactory.setConnectionRequestTimeout(20000);
            httpRequestFactory.setConnectTimeout(20000);
            httpRequestFactory.setReadTimeout(20000);
            RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
            //发送请求
            //Send the request
restTemplate.postForEntity("http://服务器ip:8868/predict/ocr_system", request, Map.class).getBody();
            System.out.println(json);
            //解析Json返回值
            //Parse the Json return value
            List<List<Map>> json1 = (List<List<Map>>) json.get("results");
            //获取文件目录为后面画图做准备
            //Get the file directory to prepare for later drawing
            String tarImgPath = destFile.toString();
            File srcImgFile = new File(tarImgPath);
            System.out.println(srcImgFile);
            //文件流转化为图片
            //The file flows into images
            Image srcImg = ImageIO.read(srcImgFile);
            //获取图片的宽
            //Gets the width of the image
            int srcImgWidth = srcImg.getWidth(null);
            //获取图片的高
            //Get the height of the image
            int srcImgHeight = srcImg.getHeight(null);
            //开始绘图主流程,创建画板设置画笔颜色等
            //Start drawing main flow, create artboard, set brush color, etc
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.setColor(Color.red);
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            //循环遍历出所有内容
            //Loop through everything
            Pattern pattern1 = Pattern.compile("\\d{2}-\\d{2}\\d{2}:\\d{2}:\\d{2}");
            for (int i = 0; i < json1.get(0).size(); i++) {
                System.out.println("当前的文字是:" + json1.get(0).get(i).get("text"));
                Matcher matcher1 = pattern1.matcher(json1.get(0).get(i).get("text") + "");
                if (matcher1.find()) {
                    String dateStr1 = matcher1.group();
                    System.out.println("==========="+dateStr1);
                }
//                System.out.println("可能的概率为:" + json1.get(0).get(i).get("confidence"));
//                List<List<Integer>> json2 = (List<List<Integer>>) json1.get(0).get(i).get("text_region");
//                System.out.println("文字的坐标" + json2);
//                int x = json2.get(0).get(0);
//                int y = json2.get(0).get(1);
//                int w = json2.get(1).get(0)-json2.get(0).get(0);
//                int h = json2.get(2).get(1)-json2.get(0).get(1);
//                g.drawRect(x,y,w,h);  //画出水印   Draw the watermark
            }
            //将内容提交到前端模板引擎
            //Submit the content to the front-end template engine
            g.dispose();
            // 输出图片
            //The output image
            FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
            ImageIO.write(bufImg, "png", outImgStream);
            System.out.println("画图完毕");
            outImgStream.flush();
            outImgStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        }
        return "OK";
    }
    private String ImageToBase64(InputStream imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        //Read the image byte array
        try {
            InputStream in = imgPath;
            System.out.println(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        //Base64 encoding of byte array
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        //Returns a Base64 encoded byte array string
        //System.out.println("图片转换Base64:" + encoder.encode(Objects.requireNonNull(data)));
        return encoder.encode(Objects.requireNonNull(data));
    }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/487529
推荐阅读
相关标签
  

闽ICP备14008679号