import csv
import numpy as np
from idtrackerai import ListOfBlobs
from scipy.interpolate import splev
from fishmidline import get_spline
import pandas as pd
frame_sections = pd.read_csv("frame_sections.csv")
# info about the frames
frame_sections_group1 = frame_sections[frame_sections["group_ID"] == 2]
# split into sections
list_of_blobs = ListOfBlobs.load(r"path_002\list_of_blobs.pickle")
# load the blobs
# Create an empty list to store the data
results = []
# the number of points on the midline
n_points = 10
# Loop through the frames
for idx, row in frame_sections_group1.iterrows():
frame_start = row["frame_start"]
frame_end = row["frame_end"]
for frame_number in range(frame_start, frame_end + 1):
blobs_in_frame = list_of_blobs.blobs_in_video[frame_number]
for identity in range(1, 11):
matching_blobs = [blob for blob in blobs_in_frame if identity in blob.final_identities]
if matching_blobs:
blob = matching_blobs[0]
spline_params = get_spline(blob)
head = splev(0, spline_params)
centroid = splev(0.5, spline_params)
head_adjusted = (head[0] + blob.bbox_in_frame_coordinates[0][0],
head[1] + blob.bbox_in_frame_coordinates[0][1])
centroid_adjusted = (centroid[0] + blob.bbox_in_frame_coordinates[0][0],
centroid[1] + blob.bbox_in_frame_coordinates[0][1])
delta_x = head_adjusted[0] - centroid_adjusted[0]
delta_y = head_adjusted[1] - centroid_adjusted[1]
angle_from_centroid_to_head = np.arctan2(delta_y, delta_x)
angle_from_centroid_to_head_deg = np.degrees(angle_from_centroid_to_head)
else:
head_adjusted = (np.nan, np.nan)
centroid_adjusted = (np.nan, np.nan)
angle_from_centroid_to_head_deg = np.nan
results.append([
frame_number,
identity,
head_adjusted[0],
head_adjusted[1],
centroid_adjusted[0],
centroid_adjusted[1],
angle_from_centroid_to_head_deg
])
# Save the results to a CSV file
csv_filename = "fish_midline_data.csv"
with open(csv_filename, mode='w', newline='') as file:
writer = csv.writer(file)
# Write the header row
writer.writerow(['frame', 'identity', 'head_x', 'head_y', 'centroid_x', 'centroid_y', 'angle_from_centroid_to_head_deg'])
# Write the data
writer.writerows(results)
print(f"Data saved to {csv_filename}")