ffmpegcudademo.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import cv2
  2. import numpy as np
  3. import subprocess
  4. import json
  5. import time
  6. def get_video_dimensions(video_path):
  7. """ 获取视频的宽高信息 """
  8. command = [
  9. 'ffprobe',
  10. '-v', 'error',
  11. '-select_streams', 'v:0',
  12. '-show_entries', 'stream=width,height',
  13. '-of', 'json',
  14. video_path
  15. ]
  16. result = subprocess.run(command, capture_output=True, text=True)
  17. info = json.loads(result.stdout)
  18. width = info['streams'][0]['width']
  19. height = info['streams'][0]['height']
  20. return width, height
  21. def get_video_fps(video_path):
  22. command = [
  23. 'ffprobe',
  24. '-v', 'error',
  25. '-select_streams', 'v:0',
  26. '-show_entries', 'stream=r_frame_rate',
  27. '-of', 'json',
  28. video_path
  29. ]
  30. result = subprocess.run(command, capture_output=True, text=True)
  31. info = json.loads(result.stdout)
  32. rate = info['streams'][0]['r_frame_rate']
  33. num, denom = map(int, rate.split('/'))
  34. return num / denom
  35. def decode_and_display_video_with_ffmpeg(video_path):
  36. width, height = get_video_dimensions(video_path)
  37. frame_size = width * height * 3
  38. fps = get_video_fps(video_path)
  39. frame_delay = 1.0 / fps
  40. command = [
  41. 'ffmpeg',
  42. '-hwaccel', 'cuda',
  43. '-i', video_path,
  44. '-f', 'rawvideo',
  45. '-pix_fmt', 'bgr24',
  46. '-vsync', '2',
  47. '-'
  48. ]
  49. print("Starting FFmpeg process...")
  50. video_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=10 ** 8)
  51. try:
  52. last_frame_time = time.time()
  53. while True:
  54. start_time = time.time()
  55. in_bytes = video_process.stdout.read(frame_size)
  56. if not in_bytes:
  57. print("Video ended.")
  58. break
  59. frame = np.frombuffer(in_bytes, np.uint8).reshape((height, width, 3))
  60. cv2.imshow('Video', frame)
  61. current_time = time.time()
  62. elapsed_time = current_time - last_frame_time
  63. delay = frame_delay - elapsed_time
  64. if delay > 0:
  65. time.sleep(delay)
  66. processing_time = time.time() - start_time
  67. print(f"Processing time for the frame: {processing_time:.4f} seconds")
  68. last_frame_time = current_time
  69. # Check for 'q' key press
  70. key = cv2.waitKey(1)
  71. if key & 0xFF == ord('q'):
  72. print("Exiting on user request.")
  73. break
  74. except Exception as e:
  75. print(f"An error occurred: {e}")
  76. finally:
  77. video_process.stdout.close()
  78. video_process.stderr.close()
  79. video_process.terminate()
  80. video_process.wait()
  81. cv2.destroyAllWindows()
  82. video_path = 'E:/BaiduNetdiskDownload/out.avi'
  83. decode_and_display_video_with_ffmpeg(video_path)