File size: 1,315 Bytes
6e90ebb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import os
import json

input_folder = "words"
output_folder = "ocr-text"

json_files = [file for file in os.listdir(input_folder) if file.endswith('.json')]

for json_file in json_files:
    print(f'Processing {json_file}')
    input_file_path = os.path.join(input_folder, json_file)
    output_file_path = os.path.join(output_folder, os.path.splitext(json_file)[0] + '.txt')

    with open(input_file_path, 'r') as file:
        data = json.load(file)

    words_list = data.get("words", [])

    #calculate width and height of the image
    width = data["image_rect"][2]
    height = data["image_rect"][3]

    result_strings = []
    for word in words_list:
        bbox_values = word["bbox"]

        #calculate (x,y,w,h)
        x =  int((bbox_values[0])*100/width)
        y =  int((bbox_values[1])*100/height)
        box_width =  int((abs(bbox_values[2]-bbox_values[0]))*100/width)
        box_height =  int((abs(bbox_values[3]-bbox_values[1]))*100/height)
        #convert everything to a string with appropriate spacing and text at the end
        result_string = f"{x} {y} {box_width} {box_height} {word['text']}"
        result_strings.append(result_string)

    result_string = ' '.join(result_strings)

    with open(output_file_path, 'w', encoding='utf-8') as file:
        file.write(result_string)