# -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 15:47:05 2026

@author: chuffard
"""

import pandas as pd
import cv2
import os



out_path='C:/ROI2023'

#import the files names

im_path='C:/SES_in'


def save_rois_from_df(df, im_path, out_path):
    # Ensure the output directory exists
    if not os.path.exists(out_path):
        os.makedirs(out_path)

    for index, row in df.iterrows():
        # Load the image
        img_path = os.path.join(im_path, row['file_name'])
        img = cv2.imread(img_path)
        
        if img is None:
            print(f"Skipping {row['file_name']}: Image not found.")
            continue

        # Map coordinates: xmin, ymin, xmax, ymax
        # Based on your input: [x.bbox[0], x.bbox[2], x.bbox[1], x.bbox[3]]
        xmin, ymin, xmax, ymax = map(int, row['bbox'])

        # Crop using NumPy slicing: [y1:y2, x1:x2]
        roi = img[ymin:ymax, xmin:xmax]

        # Save the cropped image
        roi_filename = f"roi_{index}_{row['file_name']}"
        cv2.imwrite(os.path.join(out_path, roi_filename), roi)
        
df = pd.read_csv('C:/SES_out/All_particle_measurements.csv') # Ensure 'bbox' is a list
save_rois_from_df(df, im_path, out_path)