thai_handwriting_dataset / convert_wang.py
kobkrit's picture
Add convert_wang.py
13da198
import os
import pandas as pd
from PIL import Image
import codecs
import numpy as np
import glob
import io
def create_dataset():
print("Starting dataset creation...")
# Create output directory for images
os.makedirs("processed_images", exist_ok=True)
# Process wang dataset
print("\nProcessing wang dataset...")
wang_csv = "./original/wang/free_dataset.csv"
if os.path.exists(wang_csv):
df_wang = pd.read_csv(wang_csv, header=None)
print(f"Found {len(df_wang)} entries in wang dataset")
data = []
file_count = 1
for i, row in df_wang.iterrows():
if i % 100 == 0:
print(f"Processing wang entry {i+1}/{len(df_wang)}")
_, text, _, filename = row
image_path = os.path.join("/Users/kobkrit/git/iapp-dataset/thai_handwriting_dataset/original/wang/free_dataset", filename)
if os.path.exists(image_path):
try:
img = Image.open(image_path)
# Convert image to PNG format
if img.format != 'PNG':
# Create a new RGB image with white background
png_img = Image.new('RGB', img.size, (255, 255, 255))
# Paste the original image onto the white background
png_img.paste(img, mask=img if img.mode=='RGBA' else None)
img = png_img
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format='PNG')
img_bytes = {"bytes":bytearray(img_byte_arr.getvalue())}
data.append({
'image': img_bytes,
'text': text,
'label_file': filename
})
# print(data)
# Save every 100 rows
if len(data) >= 100:
print(f"\nSaving batch {file_count} with {len(data)} images")
print("Converting to dataframe...")
df = pd.DataFrame(data)
print(f"Saving to parquet file train-{file_count:04d}.parquet...")
df.to_parquet(f"train-{file_count:04d}.parquet", index=False)
data = [] # Clear the data list
file_count += 1
except Exception as e:
print(f"Error processing wang image {image_path}: {e}")
# Save any remaining data
if len(data) > 0:
print(f"\nSaving final batch {file_count} with {len(data)} images")
print("Converting to dataframe...")
df = pd.DataFrame(data)
print(f"Saving to parquet file train-{file_count:04d}.parquet...")
df.to_parquet(f"train-{file_count:04d}.parquet", index=False)
print("Dataset creation complete!")
if __name__ == "__main__":
create_dataset()