reab5555 commited on
Commit
813d356
·
verified ·
1 Parent(s): ae7c4bd

Update visualization.py

Browse files
Files changed (1) hide show
  1. visualization.py +52 -47
visualization.py CHANGED
@@ -11,12 +11,22 @@ from moviepy.editor import VideoFileClip, AudioFileClip, CompositeVideoClip, Ima
11
  from moviepy.video.fx.all import resize
12
  from PIL import Image, ImageDraw, ImageFont
13
  from matplotlib.patches import Rectangle
14
- from utils import seconds_to_timecode
15
- from anomaly_detection import determine_anomalies
16
  from scipy import interpolate
17
- import gradio as gr
18
  import os
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def plot_mse(df, mse_values, title, color='navy', time_threshold=3, anomaly_threshold=4):
21
  plt.figure(figsize=(16, 8), dpi=300)
22
  fig, ax = plt.subplots(figsize=(16, 8))
@@ -67,7 +77,6 @@ def plot_mse(df, mse_values, title, color='navy', time_threshold=3, anomaly_thre
67
  ax.plot(segment_df['Seconds'], mean, color=color, linewidth=0.5)
68
  ax.fill_between(segment_df['Seconds'], mean - std, mean + std, color=color, alpha=0.1)
69
 
70
- # Rest of the function remains the same
71
  median = np.median(mse_values)
72
  ax.axhline(y=median, color='black', linestyle='--', label='Median Baseline')
73
 
@@ -127,7 +136,6 @@ def plot_mse(df, mse_values, title, color='navy', time_threshold=3, anomaly_thre
127
  plt.close()
128
  return fig, anomaly_frames
129
 
130
-
131
  def plot_mse_histogram(mse_values, title, anomaly_threshold, color='blue'):
132
  plt.figure(figsize=(16, 3), dpi=300)
133
  fig, ax = plt.subplots(figsize=(16, 3))
@@ -147,7 +155,6 @@ def plot_mse_histogram(mse_values, title, anomaly_threshold, color='blue'):
147
  plt.close()
148
  return fig
149
 
150
-
151
  def plot_mse_heatmap(mse_values, title, df):
152
  plt.figure(figsize=(20, 3), dpi=300)
153
  fig, ax = plt.subplots(figsize=(20, 3))
@@ -192,7 +199,6 @@ def plot_posture(df, posture_scores, color='blue', anomaly_threshold=3):
192
  # Create a new dataframe for posture data
193
  posture_df = pd.DataFrame({'Frame': posture_frames, 'Score': posture_scores})
194
 
195
-
196
  posture_df = posture_df.merge(df[['Frame', 'Seconds']], on='Frame', how='inner')
197
 
198
  ax.scatter(posture_df['Seconds'], posture_df['Score'], color=color, alpha=0.3, s=5)
@@ -243,6 +249,40 @@ def filter_mse_for_most_frequent_person(df, mse_embeddings, mse_posture, mse_voi
243
 
244
  return mse_embeddings_filtered, mse_posture_filtered, mse_voice_filtered
245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  def create_video_with_heatmap(video_path, df, mse_embeddings, mse_posture, mse_voice, output_folder, desired_fps, most_frequent_person_frames):
247
  print(f"Creating heatmap video. Output folder: {output_folder}")
248
 
@@ -275,6 +315,11 @@ def create_video_with_heatmap(video_path, df, mse_embeddings, mse_posture, mse_v
275
  video_frame = video.get_frame(t)
276
  heatmap_frame = create_heatmap(t, mse_embeddings_filtered, mse_posture_filtered, mse_voice_filtered, video.fps, total_frames, width)
277
  heatmap_frame_resized = cv2.resize(heatmap_frame, (width, heatmap_frame.shape[0]))
 
 
 
 
 
278
  combined_frame = np.vstack((video_frame, heatmap_frame_resized))
279
  return combined_frame
280
 
@@ -296,46 +341,6 @@ def create_video_with_heatmap(video_path, df, mse_embeddings, mse_posture, mse_v
296
  print(f"Failed to create heatmap video at: {heatmap_video_path}")
297
  return None
298
 
299
- def create_heatmap(t, mse_embeddings_filtered, mse_posture_filtered, mse_voice_filtered, fps, total_frames, width):
300
- # Normalize the MSE values
301
- mse_embeddings_norm = normalize_mse(mse_embeddings_filtered)
302
- mse_posture_norm = normalize_mse(mse_posture_filtered)
303
- mse_voice_norm = normalize_mse(mse_voice_filtered)
304
-
305
- # Debug prints
306
- print(f"mse_embeddings_norm shape: {mse_embeddings_norm.shape}")
307
- print(f"mse_posture_norm shape: {mse_posture_norm.shape}")
308
- print(f"mse_voice_norm shape: {mse_voice_norm.shape}")
309
-
310
- # Ensure combined_mse has the correct shape
311
- combined_mse = np.zeros((total_frames, width))
312
-
313
- # Adjust shapes and pad with zeros if necessary
314
- mse_embeddings_norm = pad_or_trim_array(mse_embeddings_norm, width)
315
- mse_posture_norm = pad_or_trim_array(mse_posture_norm, width)
316
- mse_voice_norm = pad_or_trim_array(mse_voice_norm, width)
317
-
318
- combined_mse[0] = mse_embeddings_norm
319
- # Assuming you combine posture and voice MSEs similarly
320
- combined_mse[1] = mse_posture_norm
321
- combined_mse[2] = mse_voice_norm
322
-
323
- # Return or use combined_mse as needed
324
- return combined_mse
325
-
326
- def normalize_mse(mse):
327
- # Your normalization logic here
328
- return mse / np.max(mse)
329
-
330
- def pad_or_trim_array(arr, target_length):
331
- if len(arr) > target_length:
332
- # Trim the array
333
- return arr[:target_length]
334
- elif len(arr) < target_length:
335
- # Pad the array with zeros
336
- return np.pad(arr, (0, target_length - len(arr)), 'constant')
337
- return arr
338
-
339
  def plot_correlation_heatmap(mse_embeddings, mse_posture, mse_voice):
340
  data = np.vstack((mse_embeddings, mse_posture, mse_voice)).T
341
  df = pd.DataFrame(data, columns=["Facial Features", "Body Posture", "Voice"])
 
11
  from moviepy.video.fx.all import resize
12
  from PIL import Image, ImageDraw, ImageFont
13
  from matplotlib.patches import Rectangle
 
 
14
  from scipy import interpolate
 
15
  import os
16
 
17
+ # Utility functions
18
+ def seconds_to_timecode(seconds):
19
+ hours = seconds // 3600
20
+ minutes = (seconds % 3600) // 60
21
+ seconds = seconds % 60
22
+ return f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}"
23
+
24
+ def determine_anomalies(values, threshold):
25
+ mean = np.mean(values)
26
+ std = np.std(values)
27
+ anomalies = np.where(values > mean + threshold * std)[0]
28
+ return anomalies
29
+
30
  def plot_mse(df, mse_values, title, color='navy', time_threshold=3, anomaly_threshold=4):
31
  plt.figure(figsize=(16, 8), dpi=300)
32
  fig, ax = plt.subplots(figsize=(16, 8))
 
77
  ax.plot(segment_df['Seconds'], mean, color=color, linewidth=0.5)
78
  ax.fill_between(segment_df['Seconds'], mean - std, mean + std, color=color, alpha=0.1)
79
 
 
80
  median = np.median(mse_values)
81
  ax.axhline(y=median, color='black', linestyle='--', label='Median Baseline')
82
 
 
136
  plt.close()
137
  return fig, anomaly_frames
138
 
 
139
  def plot_mse_histogram(mse_values, title, anomaly_threshold, color='blue'):
140
  plt.figure(figsize=(16, 3), dpi=300)
141
  fig, ax = plt.subplots(figsize=(16, 3))
 
155
  plt.close()
156
  return fig
157
 
 
158
  def plot_mse_heatmap(mse_values, title, df):
159
  plt.figure(figsize=(20, 3), dpi=300)
160
  fig, ax = plt.subplots(figsize=(20, 3))
 
199
  # Create a new dataframe for posture data
200
  posture_df = pd.DataFrame({'Frame': posture_frames, 'Score': posture_scores})
201
 
 
202
  posture_df = posture_df.merge(df[['Frame', 'Seconds']], on='Frame', how='inner')
203
 
204
  ax.scatter(posture_df['Seconds'], posture_df['Score'], color=color, alpha=0.3, s=5)
 
249
 
250
  return mse_embeddings_filtered, mse_posture_filtered, mse_voice_filtered
251
 
252
+ def normalize_mse(mse):
253
+ return mse / np.max(mse) if np.max(mse) > 0 else mse
254
+
255
+ def pad_or_trim_array(arr, target_length):
256
+ if len(arr) > target_length:
257
+ return arr[:target_length]
258
+ elif len(arr) < target_length:
259
+ return np.pad(arr, (0, target_length - len(arr)), 'constant')
260
+ return arr
261
+
262
+ def create_heatmap(t, mse_embeddings_filtered, mse_posture_filtered, mse_voice_filtered, fps, total_frames, width):
263
+ frame_index = int(t * fps)
264
+
265
+ # Normalize the MSE values
266
+ mse_embeddings_norm = normalize_mse(mse_embeddings_filtered)
267
+ mse_posture_norm = normalize_mse(mse_posture_filtered)
268
+ mse_voice_norm = normalize_mse(mse_voice_filtered)
269
+
270
+ # Ensure all arrays have the correct length
271
+ mse_embeddings_norm = pad_or_trim_array(mse_embeddings_norm, total_frames)
272
+ mse_posture_norm = pad_or_trim_array(mse_posture_norm, total_frames)
273
+ mse_voice_norm = pad_or_trim_array(mse_voice_norm, total_frames)
274
+
275
+ # Create a 3D array for the heatmap (height, width, channels)
276
+ heatmap_height = 3 # Assuming you want 3 rows in your heatmap
277
+ heatmap_frame = np.zeros((heatmap_height, width, 3), dtype=np.uint8)
278
+
279
+ # Fill the heatmap frame with color based on MSE values
280
+ heatmap_frame[0, :, 0] = (mse_embeddings_norm[frame_index] * 255).astype(np.uint8) # Red channel for facial features
281
+ heatmap_frame[1, :, 1] = (mse_posture_norm[frame_index] * 255).astype(np.uint8) # Green channel for body posture
282
+ heatmap_frame[2, :, 2] = (mse_voice_norm[frame_index] * 255).astype(np.uint8) # Blue channel for voice
283
+
284
+ return heatmap_frame
285
+
286
  def create_video_with_heatmap(video_path, df, mse_embeddings, mse_posture, mse_voice, output_folder, desired_fps, most_frequent_person_frames):
287
  print(f"Creating heatmap video. Output folder: {output_folder}")
288
 
 
315
  video_frame = video.get_frame(t)
316
  heatmap_frame = create_heatmap(t, mse_embeddings_filtered, mse_posture_filtered, mse_voice_filtered, video.fps, total_frames, width)
317
  heatmap_frame_resized = cv2.resize(heatmap_frame, (width, heatmap_frame.shape[0]))
318
+
319
+ # Ensure both frames have the same number of channels
320
+ if video_frame.shape[2] != heatmap_frame_resized.shape[2]:
321
+ heatmap_frame_resized = cv2.cvtColor(heatmap_frame_resized, cv2.COLOR_RGB2BGR)
322
+
323
  combined_frame = np.vstack((video_frame, heatmap_frame_resized))
324
  return combined_frame
325
 
 
341
  print(f"Failed to create heatmap video at: {heatmap_video_path}")
342
  return None
343
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  def plot_correlation_heatmap(mse_embeddings, mse_posture, mse_voice):
345
  data = np.vstack((mse_embeddings, mse_posture, mse_voice)).T
346
  df = pd.DataFrame(data, columns=["Facial Features", "Body Posture", "Voice"])