Skip to content

Commit 942e4f4

Browse files
committed
Add text orientation
1 parent fd43920 commit 942e4f4

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

TextRecognitionDataGenerator/computer_text_generator.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,15 @@
55
class ComputerTextGenerator(object):
66
@classmethod
77
def generate(cls, text, font, text_color, font_size, orientation, space_width):
8+
if orientation == 0:
9+
return cls.__generate_horizontal_text(text, font, text_color, font_size, space_width)
10+
elif orientation == 1:
11+
return cls.__generate_vertical_text(text, font, text_color, font_size, space_width)
12+
else:
13+
raise Exception("Unknown orientation " + str(orientation))
14+
15+
@classmethod
16+
def __generate_horizontal_text(cls, text, font, text_color, font_size, space_width):
817
image_font = ImageFont.truetype(font=font, size=font_size)
918
words = text.split(' ')
1019
space_width = image_font.getsize(' ')[0] * space_width
@@ -30,3 +39,31 @@ def generate(cls, text, font, text_color, font_size, orientation, space_width):
3039
txt_draw.text((sum(words_width[0:i]) + i * int(space_width), 0), w, fill=fill, font=image_font)
3140

3241
return txt_img
42+
43+
@classmethod
44+
def __generate_vertical_text(cls, text, font, text_color, font_size, space_width):
45+
image_font = ImageFont.truetype(font=font, size=font_size)
46+
47+
space_height = int(image_font.getsize(' ')[1] * space_width)
48+
49+
char_heights = [image_font.getsize(c)[1] if c != ' ' else space_height for c in text]
50+
text_width = max([image_font.getsize(c)[0] for c in text])
51+
text_height = sum(char_heights)
52+
53+
txt_img = Image.new('RGBA', (text_width, text_height), (0, 0, 0, 0))
54+
55+
txt_draw = ImageDraw.Draw(txt_img)
56+
57+
colors = [ImageColor.getrgb(c) for c in text_color.split(',')]
58+
c1, c2 = colors[0], colors[-1]
59+
60+
fill = (
61+
random.randint(c1[0], c2[0]),
62+
random.randint(c1[1], c2[1]),
63+
random.randint(c1[2], c2[2])
64+
)
65+
66+
for i, c in enumerate(text):
67+
txt_draw.text((0, sum(char_heights[0:i])), c, fill=fill, font=image_font)
68+
69+
return txt_img

TextRecognitionDataGenerator/data_generator.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ def generate(cls, index, text, font, out_dir, height, extension, skewing_angle,
2828
# Create picture of text #
2929
##########################
3030
if is_handwritten:
31+
if orientation == 1:
32+
raise Exception("Vertical handwritten text is unavailable")
3133
image = HandwrittenTextGenerator.generate(text)
3234
else:
3335
image = ComputerTextGenerator.generate(text, font, text_color, height, orientation, space_width)

0 commit comments

Comments
 (0)