Python- ocr识别模型(MNN模型)预测

2024-06-04 18:28
文章标签 python 模型 预测 识别 ocr mnn

本文主要是介绍Python- ocr识别模型(MNN模型)预测,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

import MNN
import cv2
import numpy as np
import timedef normlize_with_pad(img, width, height, ratio):h, w = img.shape[:2]  # 长边缩放为min_sideif h / w > height / width * ratio:val = int(img[-1,-1])try:img = cv2.resize(img, (int(ratio * height * w // h), height))img = cv2.copyMakeBorder(img, 0, 0, 0, (width - int(ratio * height * w // h)),cv2.BORDER_CONSTANT, value=[0, 0, 0])except Exception as e:print('error image shape {} {}'.format(h, w))img = cv2.resize(img, (width, height))return imgdef process(image_data, size):image_resize = normlize_with_pad(image_data, size[1],size[0], 1)input_data = np.array(image_resize)# input_data = np.ascontiguousarray(input_data)input_data = input_data.astype(np.float32)input_data = input_data / 255input_data = np.expand_dims(input_data, 0)input_data = np.expand_dims(input_data, 0)return input_datadef decode_out(str_index,logit, characters):char_list = []char_logit = []for i in range(len(str_index)):if str_index[i] != 0 and (not (i > 0 and str_index[i - 1] == str_index[i])):char_list.append(characters[str_index[i]-1])char_logit.append(logit[i].numpy())# char_l=1# for charl in char_logit:#     char_l*=charl# # print(char_l)# if not type(char_l)==int:#     char_l=char_l.numpy()#     if char_l.ndim>0:#         char_l=char_l[0]# print(char_logit)char_l=np.mean(char_logit)return ''.join(char_list),char_lif __name__ == "__main__":import torchmodel_path = 'densenet_rnn.mnn'# image_path = '61c785d7180e455aa6a7f892a44b733f_0_1713158555.jpg'image_path='OCRAExtended/0.jpg'resize = (32, 320)# characters= '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz[!"#$%&()*+.,/:;<=>?@\\^-_`{|}~]'characters= '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/:-'# characters= '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ't1 = time.time()# (1) load modelnet = MNN.nn.load_module_from_file(model_path,  ["images"], ["outputs"])# net = MNN.nn.load_module_from_file(model_path,  ["Input:0"], ["model/swin_tiny_patch4_window7_224/out/truediv:0"])# preprocessprint(image_path)image_data = cv2.imread(image_path,0)input_data = process(image_data, resize)# (2) 构建一个Var类型的占位符来保存numpy,placeholder(shape, format, dtype)# print(input_data.shape) #(1, 1, 320, 32)input_var = MNN.expr.placeholder(input_data.shape, MNN.expr.NCHW)input_var.write(input_data)# (3) cv2 read shape is NHWC, Module's need is NC4HW4, convert itinput_var = MNN.expr.convert(input_var, MNN.expr.NC4HW4)# print(input_var.shape)# (4) inferenceoutput_var = net.forward(input_var)# print(output_var.shape) #[1, 160, 37]# (5) the output from net may be NC4HW4, turn to linear layout# output_var = MNN.expr.convert(output_var, MNN.expr.NCHW)# print(output_var.shape)output_var = output_var.read()output_var = torch.tensor(output_var)# print(output_var.shape) #(80, 1, 66) #torch.Size([1, 160, 77])logit, preds = output_var.max(2)logit = torch.exp(logit)preds = preds.transpose(1, 0).contiguous().view(-1)# print(preds)lab2str,char_logit = decode_out(preds,logit,characters )# lab2str,char_logit = decode_out(preds,logit[0],characters )print(lab2str,char_logit)t2 = time.time()# ./MNNConvert -f ONNX --modelFile "kang-slim.onnx" --MNNModel "kang-slim.mnn" --bizCode MNN

参考文章:Ubuntu18.04上MNN编译与使用(Python版)_mnn使用python cpu推理 demo-CSDN博客

这篇关于Python- ocr识别模型(MNN模型)预测的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1030771

相关文章

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Python包管理工具核心指令uvx举例详细解析

《Python包管理工具核心指令uvx举例详细解析》:本文主要介绍Python包管理工具核心指令uvx的相关资料,uvx是uv工具链中用于临时运行Python命令行工具的高效执行器,依托Rust实... 目录一、uvx 的定位与核心功能二、uvx 的典型应用场景三、uvx 与传统工具对比四、uvx 的技术实

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

python判断文件是否存在常用的几种方式

《python判断文件是否存在常用的几种方式》在Python中我们在读写文件之前,首先要做的事情就是判断文件是否存在,否则很容易发生错误的情况,:本文主要介绍python判断文件是否存在常用的几种... 目录1. 使用 os.path.exists()2. 使用 os.path.isfile()3. 使用