|
import os |
|
import json |
|
import matplotlib.pyplot as plt |
|
import matplotlib.patches as patches |
|
|
|
|
|
input_folder = "words" |
|
output_folder = "ocr-text-sentence" |
|
|
|
json_files = [file for file in os.listdir(input_folder) if file.endswith('.json')] |
|
|
|
for idx, json_file in enumerate(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') |
|
img_file_path = os.path.join("images", json_file.replace("_words.json", ".jpg")) |
|
|
|
with open(input_file_path, 'r') as file: |
|
data = json.load(file) |
|
|
|
words_list = data.get("words", []) |
|
|
|
width = data["image_rect"][2] |
|
height = data["image_rect"][3] |
|
print(len(words_list)) |
|
sorted_list = sorted(words_list, key=lambda x: (x["bbox"][1], x["bbox"][0])) |
|
print(sum(len(s["text"]) for s in sorted_list)) |
|
|
|
merged_list = [] |
|
for i, item in enumerate(sorted_list): |
|
if i > 0: |
|
prev_item = sorted_list[i - 1] |
|
|
|
if abs(item["bbox"][1] - prev_item["bbox"][1]) < 4 and (item["bbox"][0] - prev_item["bbox"][2])<10: |
|
|
|
merged_item = { |
|
"bbox": [min(item["bbox"][0], merged_list[-1]["bbox"][0]), |
|
min(item["bbox"][1], merged_list[-1]["bbox"][1]), |
|
max(item["bbox"][2], merged_list[-1]["bbox"][2]), |
|
max(item["bbox"][3], merged_list[-1]["bbox"][3])], |
|
"text": merged_list[-1]["text"] + " " + item["text"] |
|
} |
|
|
|
merged_list[-1] = merged_item |
|
else: |
|
|
|
merged_list.append(item) |
|
else: |
|
|
|
merged_list.append(item) |
|
|
|
print(sum(len(s["text"]) for s in merged_list)) |
|
result_strings = [] |
|
for word in merged_list: |
|
bbox_values = word["bbox"] |
|
|
|
|
|
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) |
|
|
|
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) |
|
|
|
|