video_handler.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import cv2
  2. from deepface import DeepFace
  3. import time
  4. from moviepy.editor import VideoFileClip, concatenate_videoclips
  5. def process_video(video_url):
  6. # 打开视频流
  7. cap = cv2.VideoCapture(video_url)
  8. # 检查视频是否成功打开
  9. if not cap.isOpened():
  10. print("Error opening video stream from URL")
  11. return {}, None
  12. # 获取视频的帧率、宽度和高度
  13. fps = cap.get(cv2.CAP_PROP_FPS)
  14. width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  15. height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  16. # 获取当前时间戳
  17. timestamp = int(time.time())
  18. # 定义视频编码器和创建视频写入对象,使用MP4格式
  19. fourcc = cv2.VideoWriter_fourcc(*'mp4v')
  20. # 在输出文件名中加入时间戳
  21. output_path = f'annotated_video_{timestamp}.mp4'
  22. out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
  23. # 初始化情绪字典
  24. emotion_dict = {}
  25. frame_count = 0
  26. current_emotion = None
  27. # 循环读取视频帧
  28. while cap.isOpened():
  29. ret, frame = cap.read()
  30. if not ret:
  31. break
  32. if frame_count % 20 == 0:
  33. try:
  34. # 使用DeepFace进行情绪识别
  35. result = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False)
  36. current_emotion = result[0]['dominant_emotion']
  37. # 更新情绪字典
  38. if current_emotion in emotion_dict:
  39. emotion_dict[current_emotion] += 1
  40. else:
  41. emotion_dict[current_emotion] = 1
  42. except Exception as e:
  43. print(f"Error processing frame: {e}")
  44. if current_emotion is not None:
  45. # 在帧上显示情绪信息
  46. cv2.putText(frame, f"Emotion: {current_emotion}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
  47. # 写入标注后的帧到输出视频
  48. out.write(frame)
  49. frame_count += 1
  50. # 释放视频捕获对象和写入对象
  51. cap.release()
  52. out.release()
  53. return emotion_dict, output_path
  54. def merge_videos(video_paths):
  55. clips = []
  56. try:
  57. clips = [VideoFileClip(p) for p in video_paths]
  58. final = concatenate_videoclips(clips)
  59. output = f'merged_video_{int(time.time())}.mp4'
  60. final.write_videofile(output, threads=4, codec='libx264')
  61. return output
  62. finally:
  63. for clip in clips:
  64. clip.close()
  65. time.sleep(0.5) # 额外等待