Please use the following 2 scripts and update my scripts so that the individually calculated timestamp_offset is used throughout all calculations (e.g., in filtering_data, match_images_dataframes), we need to modify the way timestamps are handled in the data matching process. The main challenge here is that timestamp_offset depends on the line_number (which need the 2D coordinates of the tip), but tip comes from the coordinate data that hasn't been matched yet. This creates a circular dependency.
Mabe you need to change especially match_images_dataframes and helping funtions, so that they do it for single images and not for all images in the paths.
Please do, that in the main first all the images are filtered, and matched with a time_offset of 0, but the so calculated data is not saved, just the line_number is calculated for the second run, where the specific time_offset is calculated with the calculated line_number and afterwards all the images are saved.
1st Script:
import os
import re
import imageio
import pandas as pd
import numpy as np
import cv2
import matplotlib.pyplot as plt
import argparse
import glob
from src.camera_param import CameraParameters
from src.transformation.projective_geometry import project_points
from src.transformation.coordinates_loader import (
add_fiducial_coordinates,
filter_blurry,
filter_quality_recorded_trackers,
match_images_dataframes,
pre_filter_unrecorded_nir,
)
from src.selector_configs import SelectedData, SelectorParameters
from src.raw_dataset_configs import MetadataFile, RawDataFolder
from src.transformation.camera_loader import load_camera_parameters
from src.transformation.projective_geometry import add_tip_coordinates
from src.data_loader import _join_2d_positions
from src.raw_dataset_configs import CoordinateDataKeys
if not coordinate_files:
raise FileNotFoundError(f"No coordinate files found in {logs_folder} with pattern 'coord_log_led_based_*.txt'.")
Assistant
Load each file, skip if empty
raw_coordinates_dataframe_list = []
for coord_file in coordinate_files:
df = pd.read_csv(coord_file, delimiter=r"\s+")
if not df.empty:
raw_coordinates_dataframe_list.append(df)
else:
print(f"Warning: {coord_file} is empty and was skipped.")
Check if any data was loaded
if not raw_coordinates_dataframe_list:
raise ValueError("No data loaded from any coordinate files; all files are empty.")
if selector_parameters.quality_threshold is not None:
selected_data.coordinate_dataframe = filter_quality_recorded_trackers(
selected_data.coordinate_dataframe,
quality_threshold=selector_parameters.quality_threshold,
verbose=verbose,
)
if selector_parameters.movement_threshold_mm is not None:
selected_data.coordinate_dataframe = filter_blurry(
selected_data.coordinate_dataframe,
movement_threshold_mm=selector_parameters.movement_threshold_mm,
verbose=verbose,
)
if selector_parameters.join_fiducials:
add_fiducial_coordinates(selected_data, verbose=verbose)
if selector_parameters.join_tip_coordinates:
if verbose:
print("Joining tip coordinates...")
add_tip_coordinates(selected_data, corrected=False)
if selector_parameters.join_tip_correction:
add_tip_coordinates(selected_data, corrected=True)
if selector_parameters.join_2d_positions:
_join_2d_positions(
selected_data,
selector_parameters,
verbose=verbose,
)
Convert timestamps to seconds from the first timestamp
reference_time = min(timestamps)
x_values = [(t - reference_time) / 1000.0 for t in timestamps] # Convert ms to seconds
plt.figure(figsize=(10, 6))
plt.plot(x_values, metrics, marker='o', linestyle='-', color='b')
plt.title(f'{metric_name} over Time')
plt.xlabel('Time (seconds from start)')
plt.ylabel(metric_name)
plt.grid(True)
Save the plot as a PNG image file
plt.savefig(output_filename)
plt.close()
print(f"{metric_name} plot saved to {output_filename}")
def extract_timestamp(filename: str) -> int:
"""
Extracts the timestamp from the filename. Assumes the filename contains a large numeric timestamp in milliseconds.
Example: '106840846.png' -> 106840846 (milliseconds)
"""
pattern = re.compile(r'(\d+)') # Adjust this regex pattern to match the timestamp format
match = pattern.search(filename)
if match:
return int(match.group(1)) # Return timestamp as integer
return None
return project_points(tip_coordinates, camera_parameters)
The 10 pixel margin for cropping the ROI. Should be adapted based on the resolution of images.
margin = 10
if timestamps:
plot_metrics(timestamps, laplacian_blurs, "Laplacian Blur", os.path.join(output_folder, "laplacian_blur_plot.png"))
plot_metrics(timestamps, fft_blurs, "FFT Blur", os.path.join(output_folder, "fft_blur_plot.png"))
plot_metrics(timestamps, movements, "Movement", os.path.join(output_folder, "movement_plot.png"))
if name == 'main':
parser = argparse.ArgumentParser(description="Process parameters")
parser.add_argument('--file_path', type=str, required=True, help='Path to the data files.')
parser.add_argument('--output_size', type=int, required=True, help='Input size for the MV model.')
parser.add_argument('--UHD', action='store_true', help='Flag to set UHD (4K resolution).')
parser.add_argument('--output_folder', type=str, required=True, help='Path to save output images and CSV with the same subfolder structure as file_path.')
parser.add_argument('--framerate', type=float, required=True, help='Framerate input from user.')
parser.add_argument('--exposure_time', type=float, required=True, help='Exposure time input from user.')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt # Importing matplotlib for plotting
from src.raw_dataset_configs import CoordinateDataKeys, RawDataFolder
from src.selector_configs import SelectedData
def filter_blurry(coordinate_dataframe: pd.DataFrame, movement_threshold_mm: float = 7, verbose: bool = True) -> pd.DataFrame:
# Copy the dataframe to avoid modifying the original data
coordinate_dataframe = coordinate_dataframe.copy()
# Ensure that 'delta_time' is present in the dataframe
if 'delta_time' not in coordinate_dataframe.columns:
raise ValueError("delta_time column is missing in coordinate_dataframe")
# Extract rotation speeds (angular velocities) components in rad/s
rotation_speeds_columns = CoordinateDataKeys.TOOL_ROTATION_SPEED
rotation_speeds = coordinate_dataframe[rotation_speeds_columns].to_numpy()
# Extract translation speeds components
translation_speeds_columns = CoordinateDataKeys.TOOL_TRANSLATION_SPEED
translation_speeds = coordinate_dataframe[translation_speeds_columns].to_numpy()
# Confirm units and convert if necessary
translation_speeds *= 1000 # Convert from m/s to mm/s
# Extract delta_time from the dataframe
delta_times = coordinate_dataframe['delta_time'].to_numpy() # seconds
# Handle zero or very small delta_times to avoid division by zero or negligible movements
min_delta_time = 1e-6 # Minimum allowable delta_time (1 microsecond)
delta_times = np.where(delta_times < min_delta_time, min_delta_time, delta_times)
# Use your specific position vector from rotation center to tool tip (in mm)
r_tip = np.array([70, -1, 200]) # mm
# Number of frames
num_frames = rotation_speeds.shape[0]
# Repeat r_tip for each frame
r_tips = np.tile(r_tip, (num_frames, 1)) # Shape: (num_frames, 3)
# Calculate the linear velocity at the tool tip due to rotation for each frame
v_rotational = np.cross(rotation_speeds, r_tips) # rad/s x mm -> mm/s
# Calculate the total velocity at the tool tip
v_total = translation_speeds + v_rotational # mm/s
# Calculate estimated movement as speed (mm/s)
estimated_movement = np.linalg.norm(v_total, axis=1) # This is now in mm/s
coordinate_dataframe["estimated_movement"] = estimated_movement
zero_movement_indices = np.where(estimated_movement == 0)[0]
if len(zero_movement_indices) > 0:
print("Zero Movement Indices:", zero_movement_indices)
# 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
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
class Config:
arbitrary_types_allowed = True
def get_key_points_array(self) -> np.ndarray:
array = [self.tool_center, self.tool_bur_center]
if self.tool_bur_tip is not None:
array.append(self.tool_bur_tip)
if self.fiducials is not None:
array.extend(self.fiducials)
return np.array(array)
def get(self, index: int) -> list[str]:
return [key.format(index=index) for key in self.value]
class MetadataFile(BaseModel):
date: str
bur_id: str
bur_name: str
bur_level: int
attachment_id: str
tracker_id: int
bur_offset_mm: list[float]
and camaera_param:
import numpy as np
from pydantic import BaseModel
class CameraParameters(BaseModel):
rotation_vector: np.ndarray
translation_vector: np.ndarray
camera_matrix: np.ndarray
distortion_coefficients: np.ndarray
class Config:
arbitrary_types_allowed = True
Please ask if somethig missing to suggest a good solution
To address the circular dependency issue and to use individually calculated timestamp_offset throughout the calculations, we need to modify the way timestamps are handled in your data matching process. The main challenge is that timestamp_offset depends on the line_number (which requires the 2D coordinates of the tip), but the tip coordinates come from the coordinate data that hasn't been matched yet. This creates a circular dependency.
To solve this, we'll proceed in two passes:
First Pass: Preliminary Matching to Calculate line_number
Modify get_interpolated_data:
Ensure it can handle single image processing.
Use timestamp_offset = 0 to get initial interpolated data.
Loop Through Each Image:
For each image in your list:
Call get_interpolated_data with offset=0.0.
Extract the tip_2d_y value from the interpolated data.
Calculate line_number using this tip_2d_y value.
Compute the individual timestamp_offset for this image.
Store Per-Image timestamp_offset:
Save these offsets in a dictionary or list for use in the second pass.
Second Pass: Re-matching with Calculated timestamp_offset and Processing
Loop Through Each Image Again:
For each image in your list:
Retrieve the calculated timestamp_offset.
Call get_interpolated_data with this timestamp_offset.
Use the interpolated data for further processing (e.g., filtering data, calculating coordinates).
Proceed with the rest of the image processing and save the images.
By processing each image individually and calculating its specific timestamp_offset based on the preliminary data, we eliminate the circular dependency. This approach ensures that the individually calculated timestamp_offset is used throughout all calculations for each image.
Here's how you can implement this in your code:
Modifying get_interpolated_data and match_images_dataframes
Since get_interpolated_data already processes a single image, we'll focus on adjusting match_images_dataframes to process images one at a time:
We will modify the main function to include the two passes:
def main(file_path, UHD, output_size, output_folder, framerate, exposure_time):
file_list = os.listdir(file_path)
file_list.sort(key=lambda f: extract_timestamp(f))
# Load raw coordinate data
logs_folder = os.path.join(file_path, "logs")
coordinate_files = glob.glob(os.path.join(logs_folder, "coord_log_led_based_*.txt"))
if not coordinate_files:
raise FileNotFoundError(f"No coordinate files found in {logs_folder} with pattern 'coord_log_led_based_*.txt'.")
raw_coordinates_dataframe_list = []
for coord_file in coordinate_files:
df = pd.read_csv(coord_file, delimiter=r"\s+")
if not df.empty:
raw_coordinates_dataframe_list.append(df)
else:
print(f"Warning: {coord_file} is empty and was skipped.")
if not raw_coordinates_dataframe_list:
raise ValueError("No data loaded from any coordinate files; all files are empty.")
raw_coordinates_dataframe = pd.concat(raw_coordinates_dataframe_list, ignore_index=True)
# Load image list
image_folder = os.path.join(file_path, RawDataFolder.IMAGE_FOLDER)
image_list = os.listdir(image_folder)
image_list = pre_filter_unrecorded_nir(image_list, raw_coordinates_dataframe)
image_list.sort(key=lambda f: extract_timestamp(f))
total_lines = 2160 if UHD else 1080 # Set total lines based on UHD flag
per_image_timestamp_offsets = {}
line_numbers = {}
# First pass: obtain line_number and compute per-image timestamp_offsets
for image_name in image_list:
# First pass: match with timestamp_offset = 0.0
interpolated_data = get_interpolated_data(image_name, raw_coordinates_dataframe, offset=0.0)
if interpolated_data is None or interpolated_data.empty:
print(f"No interpolated data for {image_name}. Skipping.")
continue
# Get tip_2d_y
tip_2d_y = interpolated_data['tip_2d_y']
line_number = int(tip_2d_y)
# Compute timestamp_offset for this image
timestamp_offset = (1000.0 / framerate - exposure_time / 1000.0) * (line_number / total_lines) + (exposure_time / 1000.0 / 2.0)
# Store timestamp_offset and line_number
per_image_timestamp_offsets[image_name] = timestamp_offset
line_numbers[image_name] = line_number
# Second pass: process images with per-image timestamp_offsets
timestamps = []
laplacian_blurs = []
fft_blurs = []
movements = []
for image_name in image_list:
if image_name not in per_image_timestamp_offsets:
continue # Skip images without a computed timestamp_offset
timestamp_offset = per_image_timestamp_offsets[image_name]
interpolated_data = get_interpolated_data(image_name, raw_coordinates_dataframe, offset=timestamp_offset)
if interpolated_data is None or interpolated_data.empty:
print(f"No interpolated data for {image_name} after applying timestamp_offset. Skipping.")
continue
# Extract necessary data from interpolated_data
tool_center_x = interpolated_data["center_x"]
tool_center_y = interpolated_data["center_y"]
bur_tip_x = interpolated_data["tip_2d_x"]
bur_tip_y = interpolated_data["tip_2d_y"]
tool_center_3d = interpolated_data[CoordinateDataKeys.TOOL_CENTER_3D].to_numpy()
rotation_matrix = interpolated_data[CoordinateDataKeys.TOOL_ROTATION_MATRIX].to_numpy().reshape(-1, 3, 3).transpose(0, 2, 1)[0]
tool_center_2d = interpolated_data[CoordinateDataKeys.TOOL_CENTER_2D].to_numpy()
quality_value = interpolated_data["quality"]
movement_value = interpolated_data["estimated_movement"]
# Read the image
image_path = os.path.join(image_folder, image_name)
try:
image = imageio.v2.imread(image_path)
except Exception as e:
print(f"Failed to read {image_name}: {e}")
continue
timestamp = extract_timestamp(image_name)
if timestamp is not None:
timestamps.append(timestamp)
movements.append(movement_value)
# Prepare output path with subfolder
relative_path = os.path.relpath(image_path, file_path)
output_subfolder = os.path.join(output_folder, os.path.dirname(relative_path))
try:
print(f"Processed image {image_name}")
laplacian_blur, fft_blur = save_cropped_frame(
output_size,
image.shape[1],
image.shape[0],
tool_center_2d,
tool_center_3d,
rotation_matrix,
bur_tip_x,
bur_tip_y,
camera_parameters,
image,
image_name,
quality_value,
movement_value,
output_subfolder
)
laplacian_blurs.append(laplacian_blur)
fft_blurs.append(fft_blur)
# Store the calculated timestamp_offset if needed for further processing
print(f"Timestamp Offset for {image_name}: {timestamp_offset:.4f}")
except Exception as e:
print(f"Failed to process {image_name}: {e}")
# Save results and generate plots as in your original script
# ...
Adjusting Helper Functions
Ensure that all helper functions (filtering_data, filter_quality_recorded_trackers, filter_blurry, etc.) are compatible with single-image processing or adjust them accordingly. For instance, you might need to modify filter_blurry to handle single-image data and pass the necessary parameters directly.
Key Modifications
Processing Images Individually: By handling each image one at a time, we can calculate and apply the individual timestamp_offset.
Storing Offsets: Use a dictionary to map each image_name to its computed timestamp_offset and line_number.
Adjusting Functions for Single Images: Modify functions like match_images_dataframes and filtering_data to operate on single images instead of lists.
Handling the Circular Dependency
By performing an initial matching with timestamp_offset = 0, we obtain the required line_number (derived from the tip's 2D y-coordinate). This line_number then allows us to compute the correct timestamp_offset for each image, breaking the circular dependency.
Implementing Per-Image Calculations
In the second pass, we use the per-image timestamp_offset to retrieve accurate interpolated data for each image, ensuring that all subsequent calculations are based on this adjusted timestamp.
Conclusion
By restructuring your code to process images individually and introducing a two-pass system, we resolve the circular dependency. Each image is first analyzed to compute its specific timestamp_offset, which is then used for accurate data matching and processing in the second pass. This approach ensures that the individually calculated timestamp_offset is used consistently throughout all calculations.
Note: Be sure to adjust any other parts of your code that rely on batch processing to accommodate this per-image processing approach. This might include ensuring that DataFrames or arrays are properly handled when dealing with single-image data.
Feel free to ask if you need further clarification or assistance with specific parts of the code.