[OCR]Python 3 下的文字识别CnOCR

2023-12-29 06:44
文章标签 python 文字 识别 ocr cnocr

本文主要是介绍[OCR]Python 3 下的文字识别CnOCR,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

1  CnOCR

2 安装

3 实践


1  CnOCR

CnOCR 是 Python 3 下的文字识别Optical Character Recognition,简称OCR)工具包。

工具包支持简体中文繁体中文(部分模型)、英文数字的常见字符识别,支持竖排文字的识别。同时,自带了20+个训练好的识别模型,适用于不同应用场景,安装后即可直接使用。

同时,CnOCR也提供简单的训练命令供使用者训练自己的模型。

 2 安装

安装cnocr的命令如下:

pip --default-timeout=100 install cnocr -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

下述的字体文件用于实践中的中文识别结果的展示。

①字体文件

    SimSun:宋体

    Microsoft YaHei:微软雅黑

    FangSong:仿宋

    KaiTi:楷体

    STXihei:华文细黑

    STSong:华文宋体

    STKaiti:华文楷体

    STFangsong:华文仿宋

    SimHei:黑体

②下载地址

部分中文字体文件下载

链接: https://pan.baidu.com/s/1pCEreBBHPJKLmWPJmh4OPg 提取码: hope

 3 实践

  • ①代码
from cnocr import CnOcr
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont
import cv2
import numpy as np
def get_bbox(array):"将结果中的position信息的四个点的坐标信息转换"x1 = array[0][0]y1 = array[0][1]pt1 = (int(x1), int(y1))x2 = array[2][0]y2 = array[2][1]pt2 = (int(x2), int(y2))return pt1, pt2
def dealImg(img):b, g, r = cv2.split(img)img_rgb = cv2.merge([r, g, b])return img_rgb
def create_blank_img(img_w, img_h):blank_img = np.ones(shape=[img_h, img_w], dtype=np.int8) * 255# blank_img[:, img_w - 1:] = 0blank_img = Image.fromarray(blank_img).convert("RGB")blank_img = blank_img.__array__()return blank_img
def Draw_OCRResult(blank_img, pt1, pt2, text):cv2.rectangle(blank_img, pt1, pt2, color=[255, 255, 0], thickness=3)data = Image.fromarray(blank_img)draw = ImageDraw.Draw(data)fontStyle = ImageFont.truetype("ChineseFonts/simsun.ttc", size=30, encoding="utf-8")(x, y) = pt1draw.text((x+5, y+5), text=text, fill=(0, 0, 0), font=fontStyle)blank_img = np.asarray(data)# cv2.putText(img, temp["text"], pt1, cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 0), 2)return blank_img
def _main(img_path):im = cv2.imread(img_path)img_h, img_w, _ = im.shapeblank_img = create_blank_img(img_w, img_h)# 所有参数都使用默认值ocr = CnOcr()result = ocr.ocr(img_path)# print(result)for temp in result:print(temp["text"])# print(temp["score"])pt1, pt2 = get_bbox(temp["position"])blank_img = Draw_OCRResult(blank_img, pt1, pt2, temp["text"])fig = plt.figure(figsize=(10, 10))im = dealImg(im)img = dealImg(blank_img)titles = ["img", "result"]images = [im, img]for i in range(2):plt.subplot(1, 2, i + 1), plt.imshow(images[i], "gray")plt.title("{}".format(titles[i]), fontsize=20, ha='center')plt.xticks([]), plt.yticks([])# plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.3, hspace=0)# plt.tight_layout()plt.show()fig.savefig('test_results.jpg', bbox_inches='tight')
if __name__ == '__main__':_main("test.png")pass
  • ①结果图

  • ②代码
from cnocr import CnOcr
from PIL import Image, ImageDraw, ImageFont
import cv2
import numpy as np
def get_bbox(array):"将结果中的position信息的四个点的坐标信息转换"x1 = array[0][0]y1 = array[0][1]pt1 = (int(x1), int(y1))x2 = array[2][0]y2 = array[2][1]pt2 = (int(x2), int(y2))return pt1, pt2
def dealImg(img):b, g, r = cv2.split(img)img_rgb = cv2.merge([r, g, b])return img_rgb
def create_blank_img(img_w, img_h):blank_img = np.ones(shape=[img_h, img_w], dtype=np.int8) * 255# blank_img[:, img_w - 1:] = 0blank_img = Image.fromarray(blank_img).convert("RGB")blank_img = blank_img.__array__()return blank_img
def Draw_OCRResult(blank_img, pt1, pt2, text):cv2.rectangle(blank_img, pt1, pt2, color=[255, 255, 0], thickness=3)data = Image.fromarray(blank_img)draw = ImageDraw.Draw(data)fontStyle = ImageFont.truetype("ChineseFonts/simsun.ttc", size=30, encoding="utf-8")(x, y) = pt1draw.text((x+5, y+5), text=text, fill=(0, 0, 0), font=fontStyle)blank_img = np.asarray(data)# cv2.putText(img, temp["text"], pt1, cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 0), 2)return blank_img
def _main(img_path):im = cv2.imread(img_path)img_h, img_w, _ = im.shapeblank_img = create_blank_img(img_w, img_h)# 所有参数都使用默认值ocr = CnOcr()result = ocr.ocr(img_path)# print(result)for temp in result:print(temp["text"])# print(temp["score"])pt1, pt2 = get_bbox(temp["position"])blank_img = Draw_OCRResult(blank_img, pt1, pt2, temp["text"])images = np.concatenate((im, blank_img), axis=1)cv2.imwrite('OCR_result.jpg', images)
if __name__ == '__main__':_main("test.png")pass
  • ②结果图

茫茫人海,遇见便是缘,愿君事事顺心,一切都好。 感恩遇见!

这篇关于[OCR]Python 3 下的文字识别CnOCR的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

基于Python开发一个图像水印批量添加工具

《基于Python开发一个图像水印批量添加工具》在当今数字化内容爆炸式增长的时代,图像版权保护已成为创作者和企业的核心需求,本方案将详细介绍一个基于PythonPIL库的工业级图像水印解决方案,有需要... 目录一、系统架构设计1.1 整体处理流程1.2 类结构设计(扩展版本)二、核心算法深入解析2.1 自

从入门到进阶讲解Python自动化Playwright实战指南

《从入门到进阶讲解Python自动化Playwright实战指南》Playwright是针对Python语言的纯自动化工具,它可以通过单个API自动执行Chromium,Firefox和WebKit... 目录Playwright 简介核心优势安装步骤观点与案例结合Playwright 核心功能从零开始学习

Python 字典 (Dictionary)使用详解

《Python字典(Dictionary)使用详解》字典是python中最重要,最常用的数据结构之一,它提供了高效的键值对存储和查找能力,:本文主要介绍Python字典(Dictionary)... 目录字典1.基本特性2.创建字典3.访问元素4.修改字典5.删除元素6.字典遍历7.字典的高级特性默认字典

Python自动化批量重命名与整理文件系统

《Python自动化批量重命名与整理文件系统》这篇文章主要为大家详细介绍了如何使用Python实现一个强大的文件批量重命名与整理工具,帮助开发者自动化这一繁琐过程,有需要的小伙伴可以了解下... 目录简介环境准备项目功能概述代码详细解析1. 导入必要的库2. 配置参数设置3. 创建日志系统4. 安全文件名处

使用Python构建一个高效的日志处理系统

《使用Python构建一个高效的日志处理系统》这篇文章主要为大家详细讲解了如何使用Python开发一个专业的日志分析工具,能够自动化处理、分析和可视化各类日志文件,大幅提升运维效率,需要的可以了解下... 目录环境准备工具功能概述完整代码实现代码深度解析1. 类设计与初始化2. 日志解析核心逻辑3. 文件处

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数