ocr-annotation / json-to-annotation.py
tejasexpress's picture
utility scripts
6e90ebb verified
raw
history blame
1.32 kB
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)