# -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 15:47:05 2026

@author: chuffard
"""

import pandas as pd
import cv2
import os
import ast



# 1. Setup paths and data
csv_path = 'C:/SES_out/SES_out_roi.csv'
image_folder = 'C:/SES_in/'
output_folder = 'C:/ROI2023/'

if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# 2. Load the CSV
df = pd.read_csv(csv_path)



# 3. Iterate through the dataframe
for index, row in df.iterrows():
    # Load Image
    image_name = row['file_name'] # Replace with your image filename column name
    image_path = os.path.join(image_folder, image_name)
    img = cv2.imread(image_path)
    
    if img is None:
        print(f"Error loading image: {image_path}")
        continue
        
    # 4. Parse the bounding box string: "[ymin, ymax, xmin, xmax]"
    # Using ast.literal_eval safe-parses the string to a list
    bbox = ast.literal_eval(row['bounding_box'])
    
    # Extract coordinates
    ymin, ymax, xmin, xmax = bbox
    
    # 5. Crop the image using NumPy slicing [y:y+h, x:x+w]
    # Ensure coordinates are integers
    roi = img[int(ymin):int(ymax), int(xmin):int(xmax)]
    
    # 6. Save the ROI
    output_filename = f"{os.path.splitext(image_name)[0]}_roi_{index}.png"
    cv2.imwrite(os.path.join(output_folder, output_filename), roi)

print("ROI extraction complete.")
