worker.py 2.3 KB

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