ocr-annotation / dataframe.py
tejasexpress's picture
utility scripts
6e90ebb verified
raw
history blame
1.65 kB
import os
import pandas as pd
from PIL import Image
from io import BytesIO
import io
# Path to the folders containing images and captions
image_folder = "images"
ocr_folder = "ocr-text"
# List to store data
data = []
count = 0
# Iterate through images and captions
for index, image_file in enumerate(os.listdir(image_folder)):
if index >= 1000:
break
count += 1
print("adding image: " + image_file + " to dataframe" + " count: " + str(count))
image_path = os.path.join(image_folder, image_file)
# Assuming caption file names match image file names
ocr_path = os.path.join(ocr_folder, image_file.replace(".jpg", "_words.txt"))
# Read image and get image dimensions
image = Image.open(image_path)
image_width, image_height = image.size
# Read caption
with open(ocr_path, "r", encoding="utf-8") as ocr_file:
caption = ocr_file.read().strip()
# Convert image to byte array
img = Image.open(image_path)
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format=img.format)
img_byte_arr = img_byte_arr.getvalue()
# Append data to the list
data.append({
'image': img_byte_arr,
'ocr_annotation_texts': caption,
'image_height': image_height,
'image_width': image_width
})
# Create DataFrame
df = pd.DataFrame(data)
current_directory = os.getcwd()
parquet_file_name = "my_dataframe.parquet"
# Combine the current directory and the filename to create the full path
parquet_file_path = os.path.join(current_directory, parquet_file_name)
df.to_parquet(parquet_file_path, index=False)
# Display the DataFrame
print(df)