20190811-用Python生成中文汉字数据集_python中文统计分析 数据集_atlantistin的博客-程序员宅基地

技术标签: 汉字数据集  杂七杂八  GB2312  Python  

1. 前言

近期实现一个中文汉字分类的小项目,但尝试的时候却发现没有完全场景适用的数据集(主要是背景的繁复上),思索再三给出一种利用GB2312字符集(覆盖了6763个常用汉字)自动生成中文汉字数据集的方法,当然如果还需识别更多的低频汉字可寻找《汉语大字典》(共计数万个汉字)。

2. 准备

如下图所示:

在这里插入图片描述

其中主要包括三大部分:1. 用到的字体(可根据需要自行网络下载补充);2. 裁剪好的背景图像(可根据项目场景自行定义);3. GB2312汉字集。

3. 实现

3.1 环境准备

from PIL import Image, ImageDraw, ImageFont, ImageFilter
import numpy as np
import glob as gb
import shutil
import cv2
import os

其中主要用到了numpy和PIL库,本打算不用opencv但试了一下发现难以实现汉字的错切也没能找到合适的中文斜体字,当然直接用PIL库的主要目的是其对中文路径支持比较好,方便写入对应的汉字目录。

3.2 字体集尺寸设置及目录准备

没什么好说的,直接上代码:

# 汉字集图像尺寸
height, width = 64, 64
ziti_size = height // 4 * 3
hanzi_size = (height, width)
hanzi_shape = (height, width, 3)

# 准备生成目录
data_directory = "data"
if os.path.exists(data_directory):
    shutil.rmtree(data_directory)
    os.makedirs(data_directory)

3.3 背景和汉字的生成

# 背景准备
back_directory = "back"
def gener_back():
    back_imgpaths = gb.glob(os.path.join(back_directory, "*"))
    total_bakimgs = len(back_imgpaths)
    while True:
        yield Image.open(back_imgpaths[np.random.randint(total_bakimgs)]).resize(hanzi_size)

# 汉字生成
ziti_directory = "ziti"
def gener_ziti(zi, n=3):
    ziti_paths = gb.glob(os.path.join(ziti_directory, "*"))
    ziti_total = len(ziti_paths)
    while True:
        if n <= 0:
            break
        else:
            n -= 1
        # 添加字
        _img = Image.fromarray(np.zeros(hanzi_shape, dtype="u1"))
        font = ImageFont.truetype(ziti_paths[np.random.randint(ziti_total)], ziti_size, encoding="utf-8")
        r, g, b = np.random.randint(150, 255), np.random.randint(150, 255), np.random.randint(150, 255)
        draw = ImageDraw.Draw(_img)
        draw.text((5, 5), zi, (r, g, b), font=font)
        # 若不使用旋转可注释掉
        _img = _img.rotate(np.random.randint(-45, 45))
        # 若不使用模糊可注释掉
        _img = _img.filter(ImageFilter.GaussianBlur(radius=0.7))
        # 若不使用错切可注释掉
        theta = np.random.randint(-15, 15) * np.pi / 180
        M_shear = np.array([[1, np.tan(theta), 0], [0, 1, 0]], dtype=np.float32)
        _img = Image.fromarray(cv2.warpAffine(np.array(_img), M_shear, hanzi_size))
        yield _img

在这里使用了yield关键词,可根据情况另行搜索文章重点掌握以下,此处最大的好处是方便随机生成,当然其它功能如节省内存之类此处不表。

3.4 汉字集生成

有了前面的准备,就可以遍历所有汉字生成整个数据集啦!

# 数据集
data_directory = "data"
with open("GB2312.txt", 'r', encoding="utf-8") as fr:
    zi_sets = fr.read()
for i, zi in enumerate(zi_sets):
    # 目录准备
    zi_directory = os.path.join(data_directory, zi)
    if not os.path.exists(zi_directory):
        os.makedirs(zi_directory)
    # 开始生成
    for serial, (ziti, back) in enumerate(zip(gener_ziti(zi, n=5), gener_back())):  # n=5, 生成5张/字体
        img = Image.fromarray(np.array(ziti) // 5 * 3 + np.array(back) // 5 * 2)
        img_path = os.path.join(zi_directory, str(serial) + ".jpg")
        img.save(img_path, "JPEG")
    # 调试时用于控制生成汉字种类个数
    if i > 3:
        break

注意可以通过设置 n 的值控制每个字生成多少张,还有最后处通过 i 控制演示生成多少个,实际用的时候注释掉就OK啦!

3.5 结果

最后看一下生成的结果吧 ?

注意可以通过设置 n 的值控制每个字生成多少张,还有最后处通过 i 控制演示生成多少个,实际用的时候注释掉就OK啦!

在这里插入图片描述

6. 附注

所有代码已放置个人github:https://github.com/atlantistin/Blogs

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/atlantistin/article/details/99431866

智能推荐

解决python问题:HTTPSConnectionPool(host=‘finance.yahoo.com‘, port=443): Read timed out. (read timeout=30_readtimeout: httpsconnectionpool(host='finance.yah-程序员宅基地

检查pip有没安装cryptography,pyOpenSSL,certifi要是没有先安装pip install cryptographypip install pyOpenSSLpip install certifi我安装完上述三个包后就解决问题了。_readtimeout: httpsconnectionpool(host='finance.yahoo.com', port=443): read t

解决Ubuntu18.04与Windows之间无法复制粘贴问题_error while copying_Cool2050的博客-程序员宅基地

1.打开终端2.输入下列命令sudo apt-get autoremove open-vm-tools //卸载已有的工具sudo apt-get install open-vm-tools //安装工具open-vm-toolssudo apt-get install open-vm-tools-desktop //安装open-vm-tools-desktop3.重启ubuntureboot..._error while copying

Auxiliary Vectors 辅助向量 auvx_linux内核辅助向量-程序员宅基地

原页面http://articles.manugarg.com/aboutelfauxiliaryvectors.htmlELF auxiliary vectors are a mechanism to transfer certain kernel level information to the user processes. An example of such an info..._linux内核辅助向量

初识SQL Server代理&作业_sqlserver作业-程序员宅基地

别人写的程序在数据库中生成了一些表,并且会不停更新表中数据。现在有个需求,定期根据表中的数据做一些运算,然后重新生成一张表。我将新表的表名、字段给第三方使用。关键是,我无法修改别人的代码,好在我可以登录该系统所运行电脑的数据库。经过一番搜索后,我发现了触发器和SQL Server代理这两种工具。进一步分析后,觉得SQL Server代理可能更符合我的需求。注意本文不讨论多SQL Server实例的情况。_sqlserver作业

NIO的实现原理_nio实现原理-程序员宅基地

NIO的实现原理_nio实现原理

常见的中间件有哪些_中间件软件有哪些-程序员宅基地

常见的中间件有哪些1.一般本地开发的话,小项目,或者是个人开发建议使用tomcat。2.linux系统建议使用jetty或apache hpptd3.大型的项目就用JBOSS或webloigc4.大项目或者商业项目一般采用:weblgoic/webshere,其他的还有jboss、glasshfish等5.一些示例项目或者小项目常采用jetty6.tomcat , jboss, weblogic, websphere 一般项目tomcat就可以了Tomcat是Sun的JSWDK(._中间件软件有哪些

随便推点

剑指 Offer 24. 反转链表-程序员宅基地

节点类型:/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */第一种方法:创建一个头结点,使用遍历原链表,使用头插法,重新构建链表,实现反转。//定义一个头结点,遍历链表,将链表的节点头插到新的链表中//借助一个头结点public ListNode

记录安装SUNLIME 插件 Emmet 报错:Error while loading PyV8 binary_lime报错-程序员宅基地

今天在尝试安装sunblime插件报错 Error while loading PyV8 binary:exit code 4Try to manually install PyV8 from https://github.com/emmetio/pyv8-binaries/根据提示打开网址https://github.com/emmetio/pyv8-binaries/选择适合自己的版本选择之后发现资源已经是没有的了,另外搜索了资料,下载好适合自己的安装包把安装包解压之后放在新建好的叫Py_lime报错

线程同步和线程通信_线程通信和线程同步-程序员宅基地

线程同步安全问题解决办法:1.同步代码块:Runnable()继承2.同步方法Runnable()继承懒汉单例模式变成线程安全的问题的提出例 题模拟火车站售票程序,开启三个窗口售票。public class Rwindow implements Runnable { private int ticket =3; @Override public void run() { while(ticket>0){ System.ou_线程通信和线程同步

html 标签引用外部文件时//的作用_html*/-程序员宅基地

html 标签引用外部文件时//的作用在HTML 文件中时常会用到一系列图片,大多数时候都是使用相对路径或者绝对路径来加载对应的js css,还有img图片. 引用就不需多言 下面看一下引用的方式src="./*" 相对路径引用src="/*" 绝对路劲引用src="http://*" http 引用src="https://*" https 引用src="//*" 兼容模式引用那么兼_html*/

Oracle10g RAC环境下 DataGuard备库搭建实例-4-自己补-程序员宅基地

补充说明:==oracle官方配置===lvlisong==(2006年发布的,应该是9版本的===)1.tnsname.ora配置CHICAGO1_SERV = (DESC..._10g备库搭建

JWT、JWE、JWS 、JWK 都是什么鬼?还傻傻分不清?_互联网架构的博客-程序员宅基地

上一篇:MySQL这样写UPDATE语句,劝退作者:NinthDevilHunster来源:www.freebuf.com/articles/web/180874.htmlJWT 相信很多..._jwe