-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
168 lines (131 loc) · 5.1 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import numpy as np
import os
import pandas as pd
import matplotlib.pyplot as plt
import cv2
def getBounds(geometry):
try:
arr = np.array(geometry).T
xmin = np.min(arr[0])
ymin = np.min(arr[1])
xmax = np.max(arr[0])
ymax = np.max(arr[1])
return (xmin, ymin, xmax, ymax)
except:
return np.nan
def getWidth(bounds):
try:
(xmin, ymin, xmax, ymax) = bounds
return np.abs(xmax - xmin)
except:
return np.nan
def getHeight(bounds):
try:
(xmin, ymin, xmax, ymax) = bounds
return np.abs(ymax - ymin)
except:
return np.nan
def plot_curves(directory, color='sienna', separate_subplots=True):
# Get a list of CSV files in the directory and sort them
csv_files = sorted([file for file in os.listdir(directory) if file.endswith('.csv')])
color_map = {
0: 'blue',
1: 'red',
2: 'green',
3: 'black',
4: 'gray',
5: 'brown',
6: 'violet',
7: 'skyblue'
}
if separate_subplots:
# Calculate the number of subplots needed based on the number of CSV files
num_files = len(csv_files)
num_rows = (num_files // 2) + (1 if num_files % 2 != 0 else 0)
num_cols = min(num_files, 2)
# Create subplot grid
fig, axs = plt.subplots(num_rows, num_cols, figsize=(15, 10))
axs = axs.flatten()
# Iterate over sorted CSV files and plot curves
for i, csv_file in enumerate(csv_files):
# Construct the full path to the CSV file
csv_path = os.path.join(directory, csv_file)
# Read CSV file into a DataFrame
df = pd.read_csv(csv_path)
# Extract relevant columns
steps = df['Step']
values = df['Value']
# Plotting the curve with the specified color
axs[i].plot(steps, values, color=color_map[i])
axs[i].set_title(os.path.splitext(csv_file)[0]) # Use file name as title
axs[i].grid(True)
# Customize the plot
plt.tight_layout()
plt.show()
else:
# Create a single plot for all curves
fig, ax = plt.subplots(figsize=(15, 10))
# Iterate over CSV files and plot curves with different colors
for i, csv_file in enumerate(csv_files):
# Construct the full path to the CSV file
csv_path = os.path.join(directory, csv_file)
# Read CSV file into a DataFrame
df = pd.read_csv(csv_path)
# Extract relevant columns
steps = df['Step']
values = df['Value']
# Plotting each curve with a different color
ax.plot(steps, values, label=os.path.splitext(csv_file)[0], color=color_map[i])
# Customize the plot
plt.legend(fontsize=26, loc='lower right')
plt.xlabel("Epochs", fontsize=24)
plt.ylabel("Values", fontsize=24)
plt.ylim(0, 1)
plt.xlim(0, 500)
plt.xticks(fontsize=24)
plt.yticks(fontsize=24)
plt.grid(True)
plt.savefig("output_fig.png")
plt.show()
def concatenate_videos(videos_folder, output_folder="./md_vizualiser"):
# Create the output folder if it doesn't exist
os.makedirs(output_folder, exist_ok=True)
# Get the list of video files in the folder
video_files = [f for f in os.listdir(videos_folder) if f.endswith(".mp4") and f.startswith("Barcelona_airport_")]
# Sort the files to ensure consistent ordering
video_files.sort()
# Iterate through pairs of video files and concatenate them horizontally
for i in range(0, len(video_files), 2):
video1 = cv2.VideoCapture(os.path.join(videos_folder, video_files[i]))
# Check if the video file was opened successfully
if not video1.isOpened():
print(f"Error: Could not open {video_files[i]}")
continue
video2 = cv2.VideoCapture(os.path.join(videos_folder, video_files[i + 1]))
# Check if the video file was opened successfully
if not video2.isOpened():
print(f"Error: Could not open {video_files[i + 1]}")
video1.release()
continue
# Get the video properties
width = int(video1.get(3))
height = int(video1.get(4))
# Create an output video writer
output_path = os.path.join(output_folder, f"concatenated_{i//2}.mp4")
output_video = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*"mp4v"), 30, (width * 2, height))
while True:
ret1, frame1 = video1.read()
ret2, frame2 = video2.read()
if not ret1 or not ret2:
break
# Concatenate frames horizontally
concatenated_frame = cv2.hconcat([frame1, frame2])
# Write the concatenated frame to the output video
output_video.write(concatenated_frame)
# Release video captures and writer
video1.release()
video2.release()
output_video.release()
print("Concatenation complete.")
# Example usage:
# concatenate_videos("path/to/your/videos/folder")