|
4 | 4 | from PIL import Image, ImageFilter, ImageStat |
5 | 5 |
|
6 | 6 | from trdg import computer_text_generator, background_generator, distorsion_generator |
| 7 | +from trdg.utils import mask_to_bboxes |
7 | 8 |
|
8 | 9 | try: |
9 | 10 | from trdg import handwritten_text_generator |
@@ -52,6 +53,7 @@ def generate( |
52 | 53 | stroke_width=0, |
53 | 54 | stroke_fill="#282828", |
54 | 55 | image_mode="RGB", |
| 56 | + output_bboxes=0, |
55 | 57 | ): |
56 | 58 | image = None |
57 | 59 |
|
@@ -248,24 +250,36 @@ def generate( |
248 | 250 | if space_width == 0: |
249 | 251 | text = text.replace(" ", "") |
250 | 252 | if name_format == 0: |
251 | | - image_name = "{}_{}.{}".format(text, str(index), extension) |
252 | | - mask_name = "{}_{}_mask.png".format(text, str(index)) |
| 253 | + name = "{}_{}".format(text, str(index)) |
253 | 254 | elif name_format == 1: |
254 | | - image_name = "{}_{}.{}".format(str(index), text, extension) |
255 | | - mask_name = "{}_{}_mask.png".format(str(index), text) |
| 255 | + name = "{}_{}".format(str(index), text) |
256 | 256 | elif name_format == 2: |
257 | | - image_name = "{}.{}".format(str(index), extension) |
258 | | - mask_name = "{}_mask.png".format(str(index)) |
| 257 | + name = str(index) |
259 | 258 | else: |
260 | 259 | print("{} is not a valid name format. Using default.".format(name_format)) |
261 | | - image_name = "{}_{}.{}".format(text, str(index), extension) |
262 | | - mask_name = "{}_{}_mask.png".format(text, str(index)) |
| 260 | + name = "{}_{}".format(text, str(index)) |
| 261 | + |
| 262 | + image_name = "{}.{}".format(name, extension) |
| 263 | + mask_name = "{}_mask.png".format(name) |
| 264 | + box_name = "{}_boxes.txt".format(name) |
| 265 | + tess_box_name = "{}.box".format(name) |
| 266 | + |
263 | 267 |
|
264 | 268 | # Save the image |
265 | 269 | if out_dir is not None: |
266 | 270 | final_image.save(os.path.join(out_dir, image_name)) |
267 | 271 | if output_mask == 1: |
268 | 272 | final_mask.save(os.path.join(out_dir, mask_name)) |
| 273 | + if output_bboxes == 1: |
| 274 | + bboxes = mask_to_bboxes(final_mask) |
| 275 | + with open(os.path.join(out_dir, box_name), "w") as f: |
| 276 | + for bbox in bboxes: |
| 277 | + f.write(" ".join([str(v) for v in bbox]) + "\n") |
| 278 | + if output_bboxes == 2: |
| 279 | + bboxes = mask_to_bboxes(final_mask, tess=True) |
| 280 | + with open(os.path.join(out_dir, tess_box_name), "w") as f: |
| 281 | + for bbox, char in zip(bboxes, text): |
| 282 | + f.write(" ".join([char] + [str(v) for v in bbox] + ['0']) + "\n") |
269 | 283 | else: |
270 | 284 | if output_mask == 1: |
271 | 285 | return final_image, final_mask |
|
0 commit comments