camera.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import subprocess as sp
  2. import time
  3. import cv2
  4. import argparse
  5. # 解析参数
  6. parser = argparse.ArgumentParser()
  7. parser.add_argument("-i","--inputUrl", help="url of input rtsp url", default="0", type=str, required=False)
  8. parser.add_argument("-r","--relayUrl", help="url of the video relay server", default="", type=str, required=True)
  9. parser.add_argument("-d","--debug", help="debug mode, True or False, set to False in prod env", default=False, type=bool, required=False)
  10. parser.add_argument("-s","--sampleInterval",help="sample 1 frame every n frames of the video, the bigger the more stuck", default=4, type=int,required=False)
  11. args = parser.parse_args()
  12. print(args)
  13. inputUrl = 0 if args.inputUrl=="0" else args.inputUrl
  14. relayUrl = args.relayUrl
  15. debug = args.debug
  16. sampleInterval = args.sampleInterval
  17. # 打开视频
  18. cap=cv2.VideoCapture(inputUrl)
  19. # 执行ffmpeg管道命令
  20. command= [
  21. 'ffmpeg',
  22. '-f', 'rawvideo',
  23. '-vcodec', 'rawvideo',
  24. '-pix_fmt', 'bgr24',
  25. '-s', '428x240',
  26. '-r','30',
  27. '-i', '-',
  28. '-r','30',
  29. '-q', '0',
  30. '-codec:v', 'mpeg1video',
  31. '-f', 'mpegts',
  32. relayUrl
  33. ]
  34. pipe = sp.Popen(command,stdin=sp.PIPE)
  35. # 启动推流子进程,不断推流
  36. time.sleep(1)
  37. frame_counter = 0
  38. while (cap.isOpened()):
  39. # print("+++++++++++++", frame_counter)
  40. ret, frame = cap.read()
  41. if not ret:
  42. print("not ret")
  43. break
  44. # 1. 图像写入管道
  45. # 模n采样
  46. if frame_counter%sampleInterval==0:
  47. try:
  48. frame = cv2.resize(frame, (428, 240))
  49. if debug:
  50. cv2.imshow("debug",frame)
  51. if cv2.waitKey(1)==ord("q"):
  52. print("quit")
  53. break
  54. pipe.stdin.write(frame.tostring())
  55. except Exception as e:
  56. print("may be broken pipe")
  57. print(e)
  58. break
  59. frame_counter = (frame_counter+1)%4
  60. print("break out")
  61. cap.release()
  62. if debug:
  63. cv2.destroyAllWindows()
  64. pipe.terminate()