the logs-folder is not directly in the input of --file_path, but it is in subfolders, this is why the following script works, but your is saying that: raise FileNotFoundError(f"No coordinate files found in {logs_folder} with pattern 'coord_log_led_based_.txt'.")
FileNotFoundError: No coordinate files found in IB_experiments/dynamic/logs with pattern 'coord_log_led_based_.txt'. SCRIPT which works loading logs: 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
# Define the path to the logs folder where the coordinate files are located
logs_folder = os.path.join(data_folder, "logs")
# Find all coordinate files within the 'logs' subfolder
coordinate_files = glob.glob(os.path.join(logs_folder, "coord_log_led_based_*.txt"))
# Check if any files were found
if not coordinate_files:
raise FileNotFoundError(f"No coordinate files found in {logs_folder} with pattern 'coord_log_led_based_*.txt'.")
# 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.")
# Concatenate all dataframes into one
raw_coordinates_dataframe = pd.concat(raw_coordinates_dataframe_list, ignore_index=True)
if image_list is None:
image_list = os.listdir(image_folder)
image_list = pre_filter_unrecorded_nir(image_list, raw_coordinates_dataframe)
metadata = MetadataFile.parse_obj({
'date': '2023-10-19:14-45-32',
'bur_id': '107-030',
'bur_name': 'match head 3.0',
'bur_level': '1',
'attachment_id': '284',
'tracker_id': '0',
'bur_offset_mm': [0, 0, -1.5]
})
tip_coordinates = np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[calibration_data[2], calibration_data[0], calibration_data[1], 1]
])
camera_parameters = load_camera_parameters(camera_configuration_file)
selected_data = SelectedData(
data_folder=data_folder,
image_folder=image_folder,
coordinate_dataframe=match_images_dataframes(
image_list, raw_coordinates_dataframe, offset=offset
),
camera_parameters=camera_parameters,
metadata=metadata,
tip_coordinates=tip_coordinates,
)
if verbose:
print(
f"Found {selected_data.coordinate_dataframe.shape[0]} matches in {data_folder} across {len(coordinate_files)} files."
)
return selected_data
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,
)
return selected_data
def plot_metrics(timestamps, metrics, metric_name, output_filename):
# 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
code
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
if name == 'main':
parser = argparse.ArgumentParser(description="Process parameters")
code
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.')
args = parser.parse_args()
main(args.file_path, args.UHD, args.output_size, args.output_folder)
It seems that the issue arises because your coordinate files are located in subdirectories under your data_folder, not directly under data_folder/logs. The current implementation of your script only searches for coordinate files in the logs folder directly under data_folder. This is why you're encountering the FileNotFoundError.
To fix this, you need to modify your script to search recursively through all subdirectories under data_folder to find the coordinate files. Here's how you can adjust your load_raw_data function to achieve this:
python
def load_raw_data(
calibration_data,
data_folder: str,
offset: float = 0.0,
verbose: bool = True,
image_list: list[str] | None = None,
) -> SelectedData:
image_folder = os.path.join(data_folder, RawDataFolder.IMAGE_FOLDER)
camera_configuration_file = os.path.join(
data_folder, RawDataFolder.CAMERA_CONFIGURATION_FILE
)
# Use glob to recursively find all coordinate files matching the pattern
coordinate_files = glob.glob(
os.path.join(data_folder, "**", "coord_log_led_based_*.txt"),
recursive=True
)
# Check if any files were found
if not coordinate_files:
raise FileNotFoundError(
f"No coordinate files found under {data_folder} with pattern 'coord_log_led_based_*.txt'."
)
# Rest of your code remains the same...
By using glob.glob with the recursive=True parameter and the ** wildcard, you're instructing Python to search through all subdirectories under data_folder for files matching your pattern.
Here's the full updated load_raw_data function:
python
def load_raw_data(
calibration_data,
data_folder: str,
offset: float = 0.0,
verbose: bool = True,
image_list: list[str] | None = None,
) -> SelectedData:
image_folder = os.path.join(data_folder, RawDataFolder.IMAGE_FOLDER)
camera_configuration_file = os.path.join(
data_folder, RawDataFolder.CAMERA_CONFIGURATION_FILE
)
# Use glob to recursively find all coordinate files matching the pattern
coordinate_files = glob.glob(
os.path.join(data_folder, "**", "coord_log_led_based_*.txt"),
recursive=True
)
# Check if any files were found
if not coordinate_files:
raise FileNotFoundError(
f"No coordinate files found under {data_folder} with pattern 'coord_log_led_based_*.txt'."
)
# 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.")
# Concatenate all dataframes into one
raw_coordinates_dataframe = pd.concat(raw_coordinates_dataframe_list, ignore_index=True)
if image_list is None:
image_list = os.listdir(image_folder)
image_list = pre_filter_unrecorded_nir(image_list, raw_coordinates_dataframe)
metadata = MetadataFile.parse_obj({
'date': '2023-10-19:14-45-32',
'bur_id': '107-030',
'bur_name': 'match head 3.0',
'bur_level': '1',
'attachment_id': '284',
'tracker_id': '0',
'bur_offset_mm': [0, 0, -1.5]
})
tip_coordinates = np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[calibration_data[2], calibration_data[0], calibration_data[1], 1]
])
camera_parameters = load_camera_parameters(camera_configuration_file)
selected_data = SelectedData(
data_folder=data_folder,
image_folder=image_folder,
coordinate_dataframe=match_images_dataframes(
image_list, raw_coordinates_dataframe, offset=offset
),
camera_parameters=camera_parameters,
metadata=metadata,
tip_coordinates=tip_coordinates,
)
if verbose:
print(
f"Found {selected_data.coordinate_dataframe.shape[0]} matches in {data_folder} across {len(coordinate_files)} files."
)
return selected_data
Explanation of Changes:
Recursive Search: Changed the coordinate_files assignment to use glob.glob with recursive=True and the ** wildcard. This tells Python to search all subdirectories under data_folder.
Error Message Update: Updated the error message to reflect that it's searching under data_folder, not just logs_folder.
Additional Notes:
Performance Consideration: If your directory structure is very large, recursively searching through all subdirectories might take some time. If you know the specific subdirectories where the logs folders are located, you can refine the search pattern to those paths.
Alternative with os.walk: If you prefer or need more control, you can use os.walk to traverse directories. Here's how you can do it:
python
coordinate_files = []
for root, dirs, files in os.walk(data_folder):
for file in files:
if fnmatch.fnmatch(file, 'coord_log_led_based_*.txt'):
coordinate_files.append(os.path.join(root, file))
With the updated code, all coordinate files inside any logs folder under data_folder will be found and processed.
Testing the Updated Script:
After updating the code, run your script again. If everything is set up correctly, it should now find all the coordinate files in the subdirectories and proceed without raising the FileNotFoundError.
Ensure Correct Paths for Image Files:
Also, make sure that when you're processing the images, the paths are correctly resolved. Since the images might also be in subdirectories, you might need to adjust how you construct the image paths.
For example, in your main function, when constructing the image path:
If image_name includes subdirectory information relative to image_folder, this should work fine. If not, you might need to adjust how you obtain image_name.
Handling Multiple Subdirectories:
If you have multiple experiments or datasets structured under data_folder, and each should be processed separately, it might be better to modify your script to process each subfolder individually by iterating over the subdirectories.
For example:
python
import os
def main(file_path, UHD, output_size, output_folder):
subfolders = [f.path for f in os.scandir(file_path) if f.is_dir()]
for subfolder in subfolders:
process_data(subfolder, UHD, output_size, output_folder)
def process_data(data_folder, UHD, output_size, output_folder):
# Your existing code to process data in data_folder
...
This way, you can process each subfolder (each experiment) separately, which might give you better control over the processing and output.
Conclusion:
By adjusting your script to search recursively for coordinate files, you can accommodate your directory structure where the logs folders are within subdirectories of data_folder. The provided code updates should resolve the FileNotFoundError you're encountering.
Let me know if you have any questions or need further assistance!