I have the following script. currently the movement is calculated with a fixed FPS value, but the translations and rotation is actually calculated with interpolatet timestamps and its poses. Does it make sense to adjust the script and use the read timestamps instead of FPS and how to do it: import os
import numpy as np
import pandas as pd
from src.raw_dataset_configs import CoordinateDataKeys, RawDataFolder
from src.selector_configs import SelectedData
for fiducial_index in fiducial_indexes:
# Filter the dataframe for the specific fiducial_index
df_filtered = dataframe[dataframe['fiducial_index'] == fiducial_index]
# Find the two closest distinct timestamps for the specific fiducial_index
closest_indices = df_filtered['time_stamp'].sub(timestamp).abs().nsmallest(2).index
closest_timestamps = df_filtered.loc[closest_indices, 'time_stamp']
if len(closest_timestamps) == 2:
lower_idx, upper_idx = closest_indices
lower_time, upper_time = closest_timestamps
# Check if lower_time and upper_time are equal to avoid division by zero
if lower_time == upper_time:
interpolated_data = df_filtered.loc[lower_idx]
else:
ratio = (timestamp - lower_time) / (upper_time - lower_time)
interpolated_data = df_filtered.loc[lower_idx] + (
df_filtered.loc[upper_idx] - df_filtered.loc[lower_idx]) * ratio
else:
interpolated_data = df_filtered.loc[closest_indices[0]]
# Add the DataFrame to the list
interpolated_frames.append(interpolated_data.to_frame().T)
# Combine all interpolated frames
combined_interpolated_data = pd.concat(interpolated_frames, axis=0)
return combined_interpolated_data
Yes, it definitely makes sense to adjust your script to use the actual timestamps from your data instead of a fixed frames-per-second (FPS) value. Using the real timestamps allows for more accurate estimation of movement between frames, especially when the frame intervals are not constant. This is particularly important when dealing with variable frame rates or when precise timing is crucial for calculations (e.g., for filtering blurry images based on movement).
Why Adjusting to Use Timestamps Makes Sense:
Variable Frame Rates: Real-world data often doesn't have perfectly uniform frame intervals. Using actual timestamps accounts for any variations in frame capture times.
Accuracy: Calculating movement using actual time differences between frames provides a more accurate estimation of movement, leading to better results in filters that depend on movement thresholds.
Consistency with Interpolated Data: Since your translations and rotations are calculated using interpolated timestamps and poses, aligning the movement estimation with these timestamps ensures consistency across your computations.
How to Adjust the Script:
You need to modify the filter_blurry function to use the time differences between frames instead of dividing by a fixed FPS value. Here's how you can do it:
Calculate Delta Times Between Frames:
Compute the time difference (delta_time) between each frame using the timestamps in your coordinate_dataframe.
The delta_time will be an array where each element represents the time elapsed since the previous frame.
Compute Estimated Movement Using Delta Times:
Replace the division by FPS with multiplication by delta_time for each frame.
Calculate the estimated movement for each frame using the actual time intervals.
Handle Edge Cases:
Ensure that the first delta_time is not zero to avoid invalid calculations. You can set it to the same as the second delta_time or a nominal small value if necessary.
Here's the adjusted filter_blurry function:
python
def filter_blurry(
coordinate_dataframe: pd.DataFrame,
movement_threshold_mm: float = 7,
verbose: bool = True,
) -> pd.DataFrame:
# Extract rotation and translation speeds
rotation_speeds = np.linalg.norm(
coordinate_dataframe[CoordinateDataKeys.TOOL_ROTATION_SPEED].to_numpy(),
axis=1
) # rad/s
translation_speeds = np.linalg.norm(
coordinate_dataframe[CoordinateDataKeys.TOOL_TRANSLATION_SPEED].to_numpy(),
axis=1
) * 1000 # Convert m/s to mm/s
# Calculate delta times between frames
timestamps = coordinate_dataframe["timestamp"].to_numpy()
delta_times = np.diff(timestamps, prepend=[timestamps[0]])
# Handle the first delta time to avoid zero division
if delta_times[0] == 0 and len(delta_times) > 1:
delta_times[0] = delta_times[1]
elif delta_times[0] == 0:
delta_times[0] = np.mean(delta_times[1:]) if len(delta_times) > 1 else 1 / FPS
# Compute estimated movement using actual delta times
estimated_movement = (
translation_speeds * delta_times
+ rotation_speeds * TOOL_LENGTH_ESTIMATION * delta_times
)
# Add the estimated movement to the dataframe
coordinate_dataframe = coordinate_dataframe.copy()
coordinate_dataframe["estimated_movement"] = estimated_movement
# Filter out frames where the estimated movement exceeds the threshold
coordinate_dataframe = coordinate_dataframe[
coordinate_dataframe["estimated_movement"] < movement_threshold_mm
]
if verbose:
print(
f"Filtering blurry images... Keeping {coordinate_dataframe.shape[0]} frames"
)
return coordinate_dataframe
This computes the time difference between each timestamp.
np.diff calculates the difference between consecutive elements.
prepend=[timestamps[0]] ensures that delta_times has the same length as the original data.
Handling the First Delta Time:
The first delta_time might be zero (especially if timestamps[0] is the same as the prepended value), which can lead to issues.
The code checks if delta_times[0] is zero and assigns it a reasonable value:
python
if delta_times[0] == 0 and len(delta_times) > 1:
delta_times[0] = delta_times[1]
elif delta_times[0] == 0:
delta_times[0] = np.mean(delta_times[1:]) if len(delta_times) > 1 else 1 / FPS
Replacing the Division by FPS:
In your original code, the estimated movement was divided by FPS to get movement per frame.
The adjusted code multiplies the translation and rotation speeds by the actual delta_time between frames, giving a movement estimate based on actual elapsed time.
Benefits of This Adjustment:
More Accurate Filtering: By basing the estimated movement on actual time intervals, the filtering of blurry images becomes more precise.
Robustness to Irregular Frame Intervals: The code becomes robust to situations where frames are not captured at regular intervals.
Alignment with Interpolated Data: Using timestamps ensures that all computations are synchronized, which is especially important when interpolating data or combining datasets.
Additional Considerations:
Ensure Timestamps are in Correct Units: Make sure that your timestamps are in seconds or adjust the units accordingly in the calculations.
Copy the DataFrame Before Modifying: To avoid modifying the original DataFrame (which can lead to unintended side effects), it's good practice to create a copy before adding new columns:
Verify the Thresholds: After adjusting the estimated movement calculation, you might need to reassess the movement_threshold_mm to ensure it still makes sense with the new calculations.
Example Usage:
Assuming your coordinate_dataframe has the necessary columns (timestamp, tool rotation and translation speeds), you can use the adjusted function as follows:
By making these adjustments, your script will more accurately filter out frames based on actual movements, leading to better data quality in subsequent analyses.