开源通用验证码识别OCR —— DdddOcr 源码赏析(二)

news/2024/9/17 7:39:43/ 标签: ocr, 机器学习, 神经网络

文章目录

  • 前言
  • DdddOcr
  • 分类识别
    • 调用识别功能
    • classification 函数源码
    • classification 函数源码解读
      • 1. 分类功能不支持目标检测
      • 2. 转换为Image对象
      • 3. 根据模型配置调整图片尺寸和色彩模式
      • 4. 图像数据转换为浮点数据并归一化
      • 5. 图像数据预处理
      • 6. 运行模型,返回预测结果
  • 总结


前言

DdddOcr 源码赏析
上文我们读到了分类识别部分的源码,这里我们继续往下进行
在这里插入图片描述

DdddOcr

DdddOcr是开源的通用验证码识别OCR
官方传送门

分类识别

调用识别功能

image = open("example.jpg", "rb").read()
result = ocr.classification(image)
print(result)

classification 函数源码

def classification(self, img, png_fix: bool = False, probability=False):if self.det:raise TypeError("当前识别类型为目标检测")if not isinstance(img, (bytes, str, pathlib.PurePath, Image.Image)):raise TypeError("未知图片类型")if isinstance(img, bytes):image = Image.open(io.BytesIO(img))elif isinstance(img, Image.Image):image = img.copy()elif isinstance(img, str):image = base64_to_image(img)else:assert isinstance(img, pathlib.PurePath)image = Image.open(img)if not self.use_import_onnx:image = image.resize((int(image.size[0] * (64 / image.size[1])), 64), Image.ANTIALIAS).convert('L')else:if self.__resize[0] == -1:if self.__word:image = image.resize((self.__resize[1], self.__resize[1]), Image.ANTIALIAS)else:image = image.resize((int(image.size[0] * (self.__resize[1] / image.size[1])), self.__resize[1]),Image.ANTIALIAS)else:image = image.resize((self.__resize[0], self.__resize[1]), Image.ANTIALIAS)if self.__channel == 1:image = image.convert('L')else:if png_fix:image = png_rgba_black_preprocess(image)else:image = image.convert('RGB')image = np.array(image).astype(np.float32)image = np.expand_dims(image, axis=0) / 255.if not self.use_import_onnx:image = (image - 0.5) / 0.5else:if self.__channel == 1:image = (image - 0.456) / 0.224else:image = (image - np.array([0.485, 0.456, 0.406])) / np.array([0.229, 0.224, 0.225])image = image[0]image = image.transpose((2, 0, 1))ort_inputs = {'input1': np.array([image]).astype(np.float32)}ort_outs = self.__ort_session.run(None, ort_inputs)result = []last_item = 0if self.__word:for item in ort_outs[1]:result.append(self.__charset[item])else:if not self.use_import_onnx:# 概率输出仅限于使用官方模型if probability:ort_outs = ort_outs[0]ort_outs = np.exp(ort_outs) / np.sum(np.exp(ort_outs))ort_outs_sum = np.sum(ort_outs, axis=2)ort_outs_probability = np.empty_like(ort_outs)for i in range(ort_outs.shape[0]):ort_outs_probability[i] = ort_outs[i] / ort_outs_sum[i]ort_outs_probability = np.squeeze(ort_outs_probability).tolist()result = {}if len(self.__charset_range) == 0:# 返回全部result['charsets'] = self.__charsetresult['probability'] = ort_outs_probabilityelse:result['charsets'] = self.__charset_rangeprobability_result_index = []for item in self.__charset_range:if item in self.__charset:probability_result_index.append(self.__charset.index(item))else:# 未知字符probability_result_index.append(-1)probability_result = []for item in ort_outs_probability:probability_result.append([item[i] if i != -1 else -1 for i in probability_result_index ])result['probability'] = probability_resultreturn resultelse:last_item = 0argmax_result = np.squeeze(np.argmax(ort_outs[0], axis=2))for item in argmax_result:if item == last_item:continueelse:last_item = itemif item != 0:result.append(self.__charset[item])return ''.join(result)else:last_item = 0for item in ort_outs[0][0]:if item == last_item:continueelse:last_item = itemif item != 0:result.append(self.__charset[item])return ''.join(result)

classification 函数源码解读

1. 分类功能不支持目标检测

if self.det:raise TypeError("当前识别类型为目标检测")

2. 转换为Image对象

 if not isinstance(img, (bytes, str, pathlib.PurePath, Image.Image)):raise TypeError("未知图片类型")if isinstance(img, bytes):image = Image.open(io.BytesIO(img))elif isinstance(img, Image.Image):image = img.copy()elif isinstance(img, str):image = base64_to_image(img)else:assert isinstance(img, pathlib.PurePath)image = Image.open(img)

3. 根据模型配置调整图片尺寸和色彩模式

 if not self.use_import_onnx:image = image.resize((int(image.size[0] * (64 / image.size[1])), 64), Image.ANTIALIAS).convert('L')else:if self.__resize[0] == -1:if self.__word:image = image.resize((self.__resize[1], self.__resize[1]), Image.ANTIALIAS)else:image = image.resize((int(image.size[0] * (self.__resize[1] / image.size[1])), self.__resize[1]),Image.ANTIALIAS)else:image = image.resize((self.__resize[0], self.__resize[1]), Image.ANTIALIAS)if self.__channel == 1:image = image.convert('L')else:if png_fix:image = png_rgba_black_preprocess(image)else:image = image.convert('RGB')
  • 如果使用dddocr的模型,则将图像调整为高度为64,同时保持原来的宽高比,同时将图片转为灰度图
  • 如果使用自己传入的模型,则根据从charsets_path读取的charset info调整图片尺寸,之后根据charset 需要调整为灰度图片或RGB模式的图片,这里png_rgba_black_preprocess也是将图片转为RGB模式
def png_rgba_black_preprocess(img: Image):width = img.widthheight = img.heightimage = Image.new('RGB', size=(width, height), color=(255, 255, 255))image.paste(img, (0, 0), mask=img)return image

4. 图像数据转换为浮点数据并归一化

image = np.array(image).astype(np.float32)
image = np.expand_dims(image, axis=0) / 255.
  • image = np.array(image).astype(np.float32):首先,将图像从PIL图像或其他格式转换为NumPy数组,并确保数据类型为float32。这是为了后续的数学运算,特别是归一化和标准化。
  • image = np.expand_dims(image, axis=0) / 255.:然后,通过np.expand_dims在第一个维度(axis=0)上增加一个维度,这通常是为了符合某些模型输入的形状要求(例如,批处理大小)。之后,将图像数据除以255,将其归一化到[0, 1]区间内。

5. 图像数据预处理

if not self.use_import_onnx:image = (image - 0.5) / 0.5
else:if self.__channel == 1:image = (image - 0.456) / 0.224else:image = (image - np.array([0.485, 0.456, 0.406])) / np.array([0.229, 0.224, 0.225])image = image[0]image = image.transpose((2, 0, 1))

这段代码主要进行了图像数据的预处理,具体地,根据是否使用私人的onnx模型(self.use_import_onnx)以及图像的通道数(self.__channel),对图像数据image进行了不同的归一化处理。这种处理在机器学习和深度学习模型中是常见的,特别是当使用预训练的模型进行推理时,需要确保输入数据与模型训练时使用的数据具有相同的分布。

  • 如果不使用私人的ONNX模型 (self.use_import_onnx 为 False, 也就是使用官方的模型)

图像数据image会先减去0.5,然后除以0.5,实现了一个简单的归一化,将图像的像素值从[0, 255]范围缩放到[-1, 1]范围。这种归一化方式可能适用于某些特定训练的模型。

  • 如果使用私人的ONNX模型 (self.use_import_onnx 为 True)
  • 首先,根据图像的通道数self.__channel进行不同的处理。
    如果图像是单通道(self.__channel == 1),则图像数据image会先减去0.456,然后除以0.224,实现另一种归一化。这种归一化参数(0.456和0.224)是针对单通道图像(如灰度图)预训练的模型所使用的。
  • 如果图像是多通道(通常是RGB三通道),则图像数据image会先减去一个包含三个值的数组[0.485, 0.456, 0.406](这些值分别是RGB三通道的均值),然后除以另一个包含三个值的数组[0.229, 0.224, 0.225](这些值分别是RGB三通道的标准差或缩放因子)。这种归一化方式是为了将图像数据标准化到常见的分布,与许多预训练的深度学习模型(如ResNet, VGG等)训练时使用的数据分布相匹配。
  • 接着,对于多通道图像,还执行了两个额外的步骤:
  • image = image[0]:由于之前通过np.expand_dims增加了一个维度,这里通过索引[0]将其移除,恢复到原始的三维形状(高度、宽度、通道数)。
  • image = image.transpose((2, 0, 1)):最后,将图像的维度从(高度、宽度、通道数)转换为(通道数、高度、宽度)。这是因为某些模型(特别是使用PyTorch等框架训练的模型)期望输入数据的维度顺序为(通道数、高度、宽度)。

6. 运行模型,返回预测结果

ort_inputs = {'input1': np.array([image]).astype(np.float32)}
ort_outs = self.__ort_session.run(None, ort_inputs)
result = []
if self.__word:for item in ort_outs[1]:result.append(self.__charset[item])
else:if not self.use_import_onnx:# 概率输出仅限于使用官方模型if probability:ort_outs = ort_outs[0]ort_outs = np.exp(ort_outs) / np.sum(np.exp(ort_outs))ort_outs_sum = np.sum(ort_outs, axis=2)ort_outs_probability = np.empty_like(ort_outs)for i in range(ort_outs.shape[0]):ort_outs_probability[i] = ort_outs[i] / ort_outs_sum[i]ort_outs_probability = np.squeeze(ort_outs_probability).tolist()result = {}if len(self.__charset_range) == 0:# 返回全部result['charsets'] = self.__charsetresult['probability'] = ort_outs_probabilityelse:result['charsets'] = self.__charset_rangeprobability_result_index = []for item in self.__charset_range:if item in self.__charset:probability_result_index.append(self.__charset.index(item))else:# 未知字符probability_result_index.append(-1)probability_result = []for item in ort_outs_probability:probability_result.append([item[i] if i != -1 else -1 for i in probability_result_index ])result['probability'] = probability_resultreturn resultelse:last_item = 0argmax_result = np.squeeze(np.argmax(ort_outs[0], axis=2))for item in argmax_result:if item == last_item:continueelse:last_item = itemif item != 0:result.append(self.__charset[item])return ''.join(result)else:last_item = 0for item in ort_outs[0][0]:if item == last_item:continueelse:last_item = itemif item != 0:result.append(self.__charset[item])return ''.join(result)
  • 使用模型预测字符并拼接字符串,官方模型可以输出概率信息

argmax_result = np.squeeze(np.argmax(ort_outs[0], axis=2))这行代码在ort_outs[0]的第三个维度(axis=2)上应用np.argmax函数,以找到序列中每个元素最可能的字符索引。np.squeeze用于去除结果中维度为1的轴


总结

本文介绍了DdddOcr的分类识别任务的源码实现过程,主要是调整图片尺寸和色彩模式,以及图像数据的预处理,最后运行模型预测得到结果,下一篇文章中我们将继续阅读DdddOcr目标检测任务的源码实现过程,天命人,明天见!
在这里插入图片描述


http://www.ppmy.cn/news/1521775.html

相关文章

DWPD指标:为何不再适用于大容量SSD?

固态硬盘(Solid State Drives, SSD)作为计算机行业中最具革命性的技术之一,凭借其更快的读写速度、增强的耐用性和能效,已经成为大多数用户的首选存储方案。然而,如同任何其他技术一样,SSD也面临自身的挑战…

C++ 栈的使用

在 C++ 中,栈(Stack)是一种后进先出(LIFO,Last In First Out)的数据结构,表示最后插入的元素最先被移除。C++ 提供了 STL(Standard Template Library)中的 std::stack 容器适配器来方便使用栈。 std::stack 的使用 std::stack 是一个容器适配器,它默认使用 std::de…

接口请求400

接口请求400 在Web开发中,接口请求错误是开发者经常遇到的问题之一。其中,400错误(Bad Request)尤为常见,它表明发送到服务器的请求有误或不能被服务器理解。本文将深入探讨接口请求400错误,从常见报错问题…

基于纠错码的哈希函数构造方案

一、前言 随着大数据时代的到来,交通数据量急剧增加,由此带来的交通安全问题日益凸显。传统的驾驶人信用管理系统在数据存储和管理上存在着诸多不足之处,例如中心化存储方案无法有效地进行信用存证及数据溯源。区块链技术以其去中心化和不可…

python网络爬虫(零)——认识网页结构

网页一般有三部分组成&#xff0c;分别是HTML&#xff08;超文本标记语言&#xff09;、CSS&#xff08;层叠样式表&#xff09;、JScript&#xff08;活动脚本语言&#xff09; 1.HTML HTML是整个网页的结构&#xff0c;相当于整个网站的框架。带“<”“>”符号都属于H…

Trying to update a textarea with string from an OpenAI request

题意&#xff1a;把从 OpenAI 请求中得到的字符串更新到一个文本区域中。 问题背景&#xff1a; Can anyone assist me with an issue Im facing. Im trying to append a string received back from an OpenAI request to an exisitng textarea element. The requested string…

设计之道:ORM、DAO、Service与三层架构的规范探索

引言&#xff1a; 实际开发中&#xff0c;遵守一定的开发规范&#xff0c;不仅可以提高开发效率&#xff0c;还可以提高项目的后续维护性以及项目的扩展性&#xff1b;了解一下本博客的项目设计规范&#xff0c;对项目开发很有意义 一、ORM思想 ORM&#xff08;Object-Relation…

P0.9/P1.25全倒装共阴节能COB超微小间距LED显示屏已抢占C位

COB&#xff08;Chip on Board&#xff09;技术最早发源于上世纪60年代&#xff0c;是将LED芯片直接封装在PCB电路板上&#xff0c;并用特种树脂做整体覆盖。COB实现“点” 光源到“面” 光源的转换。点间距有P0.3、P0.4、P0.5、P0.6、P0.7、P0.9、P1.25、P1.538、P1.5625、P1.…

pytorch计算张量中三维向量的欧式距离

如果 X 是一个包含多个三维向量的张量&#xff0c;形状为 [b, n, 3]&#xff0c;其中 b 是批次大小&#xff0c;n 是每个批次中的向量数量&#xff0c;那么可以使用类似的广播机制来计算同一批次内不同位置的三维向量之间的欧式距离。 以下是具体实现步骤&#xff1a; 扩展张量…

时序预测 | 基于DLinear+PatchTST多变量时间序列预测模型(pytorch)

目录 效果一览基本介绍程序设计参考资料 效果一览 基本介绍 DLinearPatchTST多变量时间序列 dlinear,patchtst python代码&#xff0c;pytorch架构 适合功率预测&#xff0c;风电光伏预测&#xff0c;负荷预测&#xff0c;流量预测&#xff0c;浓度预测&#xff0c;机械领域预…

Java 基于微信小程序的小区服务管理系统,附源码

博主介绍&#xff1a;✌stormjun、8年大厂程序员经历。全网粉丝15w、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专栏推荐订阅&#x1f447;&…

websocket和轮询的区别?

问&#xff1a; websocket和轮询的区别&#xff1f; 回答&#xff1a; WebSocket 和定时轮询&#xff08;每隔几秒发送一次请求&#xff09;是两种不同的实时通信方法&#xff0c;各有优缺点&#xff0c;适用于不同的场景。以下是它们的主要区别及适用场景&#xff1a; WebSo…

Node.js sqlite3事件深入解析:trace、profile、change、error、open

在Node.js环境中&#xff0c;sqlite3库不仅提供了丰富的API用于数据库操作&#xff0c;还定义了一系列的事件&#xff0c;使得开发者能够监听和响应数据库操作过程中的各种状态变化。本文将深入解析sqlite3库中的trace、profile、change、error、open这五个事件&#xff0c;包括…

0903,LIST(merge,splice,sort,unique),SET(insert,erase)

目录 03_vector_delete.cc 04_vector_shrink.cc 05_vec_emplace_back.cc 06_listspec_splice.cc 07_classstruct.cc 08_set.cc 09_setErase.cc 作业 01 STL中的容器包括哪些&#xff1f;各自具有哪些特点&#xff1f; 02 题目&#xff1a;编写代码&#xff1a;将…

Android Camera系列(一):SurfaceView+Camera

心行慈善&#xff0c;何需努力看经—《西游记》 Android Camera系列&#xff08;一&#xff09;&#xff1a;SurfaceViewCamera Android Camera系列&#xff08;二&#xff09;&#xff1a;TextureViewCamera Android Camera系列&#xff08;三&#xff09;&#xff1a;GLSur…

20240902软考架构-------软考96-100答案解析

每日打卡题96-100答案 96、【2018年真题】 难度&#xff1a;难 CORBA服务端构件模型中&#xff0c; 是CORBA对象的真正实现&#xff0c;负责完成客户端请求。 A.伺服对象&#xff08;Servant&#xff09; B.对象适配器&#xff08;Object Adapter&#xff09; C.对象请求代理&…

回溯——7.子集II

力扣题目链接 给定一个可能包含重复元素的整数数组 nums&#xff0c;返回该数组所有可能的子集&#xff08;幂集&#xff09;。 说明&#xff1a;解集不能包含重复的子集。 示例: 输入: [1,2,2]输出: [ [2], [1], [1,2,2], [2,2], [1,2], [] ] 解题思路总结&#xff1a; …

AIStarter改进计划:功能优化与内测预告【欢迎吐槽】

随着技术的不断进步&#xff0c;AIStarter也在持续进化&#xff0c;以更好地满足用户的需求。本文将探讨AIStarter的改进计划&#xff0c;包括应用版本号、市场排序、描述和筛选功能的优化&#xff0c;并预告即将到来的内测消息。此外&#xff0c;还将介绍AIStarter在网络加速、…

东南大学研究生-数值分析上机题(2023)Python 3 线性代数方程组数值解法

列主元Gauss消去法 3.1 题目 对于某电路的分析&#xff0c;归结为就求解线性方程组 R I V \pmb{RIV} RIV&#xff0c;其中 R [ 31 − 13 0 0 0 − 10 0 0 0 − 13 35 − 9 0 − 11 0 0 0 0 0 − 9 31 − 10 0 0 0 0 0 0 0 − 10 79 − 30 0 0 0 − 9 0 0 0 − 30 57 − 7 …

【2024-2025源码+文档+调试讲解】微信小程序的城市公交查询系统

摘 要 当今社会已经步入了科学技术进步和经济社会快速发展的新时期&#xff0c;国际信息和学术交流也不断加强&#xff0c;计算机技术对经济社会发展和人民生活改善的影响也日益突出&#xff0c;人类的生存和思考方式也产生了变化。传统城市公交查询管理采取了人工的管理方法…