from PIL import ImageFont,ImageDraw
import numpy as np
import PIL.Image as Image
def union(au, bu, area_intersection):
area_a = (au[2] - au[0]) * (au[3] - au[1])
area_b = (bu[2] - bu[0]) * (bu[3] - bu[1])
area_union = area_a + area_b - area_intersection
return area_union
def intersection(ai, bi):
x = max(ai[0], bi[0])
y = max(ai[1], bi[1])
w = min(ai[2], bi[2]) - x
h = min(ai[3], bi[3]) - y
if w < 0 or h < 0:
return 0
return w * h
def iou(a, b):
# a and b should be (x1,y1,x2,y2)
if a[0] >= a[2] or a[1] >= a[3] or b[0] >= b[2] or b[1] >= b[3]:
return 0.0
area_i = intersection(a, b)
area_u = union(a, b, area_i)
return float(area_i) / float(area_u + 1e-6)
def create_text_pic(pic_num,text_num,save_label_dir,save_pic_dir=''):
char='ABCDEFGHIJKLMNOPQRSTUVWZIJ111222333444555666777888999000'
char_len=len(char)
for i in range(pic_num):
new = Image.new('RGB',(600,900),color=(255,255,255))
draw = ImageDraw.Draw(new)
text_long=''
exist_area=[]
for _ in range(text_num):
fontsize1 = np.random.randint(15, 40)
font1 = ImageFont.truetype('default.ttf', fontsize1)
x1 = np.random.randint(25, 350)
y1 = np.random.randint(50, 800)
long_num=np.random.randint(9,18)
for _ in range(long_num):
text_long+=char[np.random.randint(0,char_len)]
w1, h1 = draw.textsize(text_long, font=font1)
if x1 + w1 > 600 or y1 + h1 > 900:
text_long = ''
continue
flag=0
a=[x1,y1,x1+w1,y1+h1]
for area in exist_area:
if iou(a,area)>0:
text_long=''
flag=1
break
if flag==1:
continue
exist_area.append(a)
draw.text((x1, y1), text_long, font=font1, fill='#000000')
with open(save_label_dir+'label.txt', 'a') as f:
s = ','.join(['data/'+str(i)+'.jpg',str(x1), str(y1), str(x1 + w1), str(y1 + h1), text_long])
f.write(s + '\n')
text_long=''
new.save(save_pic_dir+str(i)+'.jpg')
修改生成文本的行数可在代码中修改text_num的 值
修改文字大小可在代码中修改fontsize1的 值
修改长文字长度可修改代码中text_long的值
修改短文字长度可修改代码中text_short的值