live.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import cv2
  2. import subprocess as sp
  3. import exetract
  4. import livePipe
  5. rtspUrl = 'rtsp://localhost:8554/mystream'
  6. # 视频来源 地址需要替换自己的可识别文件地址
  7. filePath = '/Users/gemer/Desktop/'
  8. testPath = '/Users/gemer/Desktop/test-video/'
  9. camera = cv2.VideoCapture(
  10. filePath+"test.mkv") # 从文件读取视频
  11. names = ['output000.mkv', 'output001.mkv', 'output001.mkv', 'output001.mkv']
  12. # 视频属性
  13. size = (int(camera.get(cv2.CAP_PROP_FRAME_WIDTH)),
  14. int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT)))
  15. sizeStr = str(size[0]) + 'x' + str(size[1])
  16. fps = camera.get(cv2.CAP_PROP_FPS) # 30p/self
  17. # fps = 24
  18. fps = int(fps)
  19. hz = int(1000.0 / fps)
  20. print('size:' + sizeStr + ' fps:' + str(fps) + ' hz:' + str(hz))
  21. # 主视频文件输出
  22. # fourcc = cv2.VideoWriter_fourcc(*'XVID')
  23. fourcc = cv2.VideoWriter_fourcc('H', '2', '6', '4')
  24. out = cv2.VideoWriter(filePath + 'res_mv.avi', fourcc, fps, size)
  25. # caps = [cv2.VideoCapture(testPath+i) for i in names]
  26. # print('cap', caps)
  27. # for x in caps:
  28. # print(x)
  29. # fourcc = cv2.VideoWriter_fourcc('H', '2', '6', '4')
  30. # fps = int(fps)
  31. # hz = int(1000.0 / fps)
  32. # 直播管道输出
  33. # ffmpeg推送rtmp 重点 : 通过管道 共享数据的方式
  34. command = ['ffmpeg',
  35. '-y',
  36. '-hide_banner',
  37. # '-loglevel', 'warning',
  38. # '-hwaccel', 'videotoolbox',
  39. '-f', 'rawvideo',
  40. '-vcodec', 'rawvideo',
  41. '-pix_fmt', 'bgr24',
  42. '-s', sizeStr,
  43. '-r', str(fps),
  44. '-i', '-',
  45. '-b:v', '3000K',
  46. # '-c:v', 'h264_videotoolbox',
  47. '-c:v', 'libx264',
  48. '-pix_fmt', 'yuv420p',
  49. '-preset', 'ultrafast',
  50. '-f', 'rtsp',
  51. rtspUrl]
  52. # 管道特性配置
  53. # pipe = sp.Popen(command, stdout = sp.PIPE, bufsize=10**8)
  54. # pipe = sp.Popen(command, stdin=sp.PIPE, bufsize=10**8) # ,shell=False
  55. newPipe = livePipe.LivePipe(size, 30)
  56. # pipe.stdin.write(frame.tostring())
  57. while True:
  58. ret, frame = camera.read() # 逐帧采集视频流
  59. # if not ret:
  60. # break
  61. if cv2.waitKey(1) & 0xFF == ord('q'):
  62. break
  63. # 图片输出
  64. # 结果帧处理 存入文件 / 推流 / ffmpeg 再处理
  65. # print('frame', frame)
  66. newPipe.stdin.write(frame.tobytes()) # 存入管道用于直播
  67. out.write(frame) # 同时 存入视频文件 记录直播帧数据
  68. pass
  69. camera.release()
  70. # Release everything if job is finished
  71. out.release()
  72. # out.release()
  73. print("Over!")