from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
import glob
import numpy as np
import os
import cv2
from nespaper_semantics import seg_str'''
1. 从文字库随机选择10个字符
2. 生成图片
3. 随机使用函数
'''
# 从字库中随机选择n个字符
def sto_choice_from_info_str(info_str,quantity):start = random.randint(0, len(info_str)-(quantity+1))end = start + quantityrandom_word = info_str[start:end]return random_worddef random_word_color():font_color_choice = [[10, 10, 10], [5, 5, 5], [0, 0, 0]]font_color = random.choice(font_color_choice)noise = np.array([random.randint(0,2), random.randint(0,2), random.randint(0,2)])font_color = (np.array(font_color) + noise).tolist()return tuple(font_color)
# 生成一张背景图片
def create_an_image(bground_path, width, height):bground_list = os.listdir(bground_path)bground_choice = random.choice(bground_list)bground = cv2.imread(os.path.join(bground_path, bground_choice))x, y = random.randint(0, bground.shape[1]-width), random.randint(0, bground.shape[0]-height)bground = bground[y:y+height, x:x+width, :]return bground# 随机选取文字贴合起始的坐标, 根据背景的尺寸和字体的大小选择
def random_x_y(bground_size, font_size):height, width, _ = bground_sizeprint('bground_size:', bground_size)print('font_size:', font_size)# 为防止文字溢出图片,x,y要预留宽高# x = random.randint(0, width - font_size * 10)# y = random.randint(0, int((height-font_size)/4))"""====notice notice===="""#10个字要减140 9个字要减100 8个字要减80 7个字要减40 6个字要减20 5个字以下不用减x = random.randint(3, int((width - font_size) / 2))y = random.randint(10, height - font_size * 7)return x, ydef random_font_size():font_size = random.randint(22,25)return font_sizedef random_font(font_path):font_list = os.listdir(font_path)random_font = random.choice(font_list)return os.path.join(font_path, random_font)
def add_white_noise(image):rows, cols, dims = image.shaperandom_index=random.randint(10,100)for i in range(random_index):x = np.random.randint(2, rows)y = np.random.randint(2, cols)if random.getrandbits(1):image[x-1:x+1, y-1:y+1, :] = 180else:image[x, y, :] = 180return imagedef main(infostr, save_path, num,words_length,width,height,back_path,font_path):# 随机选取5个字符random_word_ori = sto_choice_from_info_str(infostr, words_length)print('random_word_ori:', random_word_ori)random_word = ''.join([i+'\n' for i in random_word_ori if i not in [':','(',')','「','」']])print('random_word:\n', random_word)# # 生成一张背景图片,已经剪裁好,宽高为280*32raw_image = create_an_image(back_path, width, height)# 随机选取字体大小font_size = random_font_size()# 随机选取字体font_name = random_font(font_path)print('font_name:', font_name)# 随机选取字体颜色font_color = random_word_color()# 随机选取文字贴合的起始坐标 x,ydraw_x, draw_y = random_x_y(raw_image.shape, font_size)# 将文本贴到背景图片raw_image = Image.fromarray(raw_image[..., ::-1])font = ImageFont.truetype(font_name, font_size)draw = ImageDraw.Draw(raw_image)draw.text((draw_x, draw_y), random_word, fill=font_color, font=font)raw_image = raw_image.rotate(0.3)image = add_white_noise(np.array(raw_image))# cv2.imwrite('image.jpg', image)# 保存文本信息和对应图片名称img_name = save_path+'/'+'fake_'+str(words_length)+'_'+str(num)+'.jpg'cv2.imwrite(img_name, image)with open(img_name.replace('.jpg','.txt'), 'w', encoding='utf-8') as file:[file.write(val) for val in random_word_ori]
def make_fake_data(total):#背景图片地址back_path = './background'#字体地址font_path = './font'#语料库 #从make_fake_word_library函数得到得到的语料库info_str = seg_strprint('len(info_str):', len(info_str))# 生成的字符个数words_length = 3output_path = 'data_set/fake_one_'+str(words_length)if not os.path.exists(output_path):os.mkdir(output_path)if words_length < 6:width=32height=200elif 6<=words_length<7:width = 32height = 220elif 7<=words_length<8:width = 32height = 240elif 8 <= words_length < 9:width = 32height = 280elif 9 <= words_length < 10:width = 32height = 300else:width = 32height = 340for i,num in enumerate(range(0, total)):if i<1:main(info_str, output_path, num, words_length, width, height,back_path,font_path)if num % 1000 == 0:print('[%d/%d]' % (num, total))
#根据标注的报纸制作语义库
def make_fake_word_library():import pandas as pdtrain_path = './label/train.txt'val_path = './label/val.txt'train_names = np.array(pd.read_csv(train_path, header=None))val_names = np.array(pd.read_csv(val_path, header=None))Semantics_list=[]for i,train_name in enumerate(train_names):words = train_name[0].split(' ')[-1]Semantics_list.append(words)for i,val_name in enumerate(val_names):words = val_name[0].split(' ')[-1]Semantics_list.append(words)print(len(Semantics_list))print(Semantics_list[:2])Semantics_str=''.join(Semantics_list)print(len(Semantics_str))print(Semantics_str)
if __name__ == '__main__':#用报纸制作的假数据make_fake_data(total=1000)# make_fake_word_library()

背景:

 

字体:https://download.csdn.net/download/fanzonghao/11866723

输出:

 

利用已有的标注文字信息制作fake数据相关推荐

  1. 【Python例】利用 python 进行图片文字信息的提取 --- OCR-EasyOCR

    [Python例]利用 python 进行图片文字信息的提取 - OCR-EasyOCR 本文主要用于记录,并使用 python 脚本进行图片文字信息的生成. 什么是 OCR? OCR OCR(Opt ...

  2. bootstranp选项卡怎么把每个选项卡里面的表单分开提交_EXCEL 宏应用基础知识,利用已实现的宏,制作自己的功能选项卡...

    前言 第一次使用excel vba编程,解决重复性的excel操作问题.虽然问题不难,但在设置宏的过程中,一点点解决了很多小问题,相信这些小问题也都可能是大家在应用该项功能中可能碰到的问题,对于在搜索 ...

  3. ocr语种识别_利用OCR图文识别,快速帮你提取文字信息

    我们在浏览网页.读书的时候,经常找到我们感兴趣的资料,有时候一些纸质文字或图片是无法复制保存的,那么为了方便这类信息的提取.编辑保存,中安未来特研发了OCR图文识别技术: 中安未来OCR图文识别技术是 ...

  4. Python之matplotlib:利用matplotlib绘制八象空间三维图案例(知识点包括散点图、折线图、标注文字、图例、三维坐标)之详细攻略

    Python之matplotlib:利用matplotlib绘制八象空间三维图案例(知识点包括散点图.折线图.标注文字.图例.三维坐标)之详细攻略 目录

  5. Python利用百度AI提取图片中的文字信息

    Python利用百度AI提取图片中的文字信息 安装百度AI : pip install baidu-aip 到https://console.bce.baidu.com/ai/创建文字识别应用,获取A ...

  6. pdf一键转曲_新技能:如何利用PDF制作可变数据!

    一提到制作可变数据,是不是就很头大?要在Excel里事先做好数据文本,设置多种功能,再利用Indesign.CorelDRAW排版制作? 今天,小编就给大家介绍一种简单方便的操作方法,仅利用PDF就能 ...

  7. 计算机网络桂电北海期末题,2078电大《网络信息制作与发布》试题和答案200407...

    试卷代号:2078 中央广播电视大学2003-2004学年度第二学期"开放专科"期末考试 计算机专业 网络信息制作与发布 试题 2004年7月 一.填空题(每空1分,共30分) 1 ...

  8. Hack The Box - Catch 利用let chat API查询信息,Cachet配置泄露漏洞获取ssh登录密码,apk代码注入漏洞利用获取root权限

    Hack The Box-Catch Hack The Box开始使用流程看这篇 文章目录 Hack The Box-Catch 整体思路 1.Nmap扫描 2.apk文件信息收集 3.lets ch ...

  9. 生成二维码附带文字信息

    生成二维码写入PDF文件 目录 生成二维码写入PDF文件 前言 一.引入依赖 二.生成二维码 1.创建实体类 2.创建QRCodeUtil 3.生成单条二维码 4.批量生产二维码 三.生成二维码写入P ...

最新文章

  1. java线程钥匙_Java多线程并发编程/锁的理解
  2. cmd启动tomcat
  3. UIImage的scale
  4. 2015 Multi-University Training Contest 1 - 10010 Y sequence
  5. AndroidStudio更换黑色主题方法
  6. StringBuffer、StringBuilder区别以及Synchronized原理
  7. 升级 | Fastjson 1.2.68 发布,支持 GEOJSON
  8. Objective-C 编码规范
  9. openfire + spark + sparkweb + pandion 下载地址
  10. 深度学习核心技术精讲100篇(四十九)-半监督学习在金融文本分类上的探索和实践
  11. 维纳滤波原理(Wiener Filter)
  12. 【技术综述】基于弱监督深度学习的图像分割方法综述
  13. 修改拦截器里的请求头_OkHttp4 源码分析(1) 请求流程分析
  14. matlab 方差,方差分解——matlab 代码
  15. zerglurker的C语言教程001——开发环境搭建
  16. Matlab画天球坐标图,知道方位角和高度角
  17. 锻炼完美腹肌的7条原则
  18. 服务器显示时间差8个小时,服务器时间相差8小时 原因与解决方法
  19. web-前端之后台管理系统模板首页
  20. DelphiXE7操作sqlite数据库

热门文章

  1. python爬虫入门必备正则_python 爬虫入门之正则表达式 一
  2. python的注释符_Python3 注释和运算符
  3. 美团大脑:知识图谱的建模方法及其应用
  4. 论文浅尝 | 基于对抗学习的弱监督知识图谱对齐
  5. bert模型简介、transformers中bert模型源码阅读、分类任务实战和难点总结
  6. 模拟退火算法求解TSP问题
  7. 2017沈阳站 Tree
  8. 企业——Docker容器的搭建及简单应用
  9. [COCI2017-2018#1] Plahte
  10. python基础--格式化输出