1

I am using a simple opencv code to read a video file from the system.

import cv2
cap = cv2.VideoCapture("1.mp4")
while True:
  res,frame = cap.imread()
  cv2.imshow("frame",frame)
  cv2.waitKey(1)

Now i want to stream this video feed to an HTTP server, so that it can be accessed by multiple users using the given URL.

I came across Flask but it supports only one user at time.

After going through various blogs, i came to know that FFSERVER and FFMPEG might solve the problem.Now i am stuck on how to send a frame to FFSERVER. I run the following command.. ffmpeg -i sintel.mp4 http://localhost:8090/feed1.ffm

But i didn't send anything to the FFSERVER.

I am using the code from this blog post

  • FFmpeg does not support FFserver anymore. They dropped it from v4.0 on wards. Although you can get it from previous versions, I would recommend looking at Gstreamer. – zindarod Sep 27 '18 at 08:50

1 Answers1

1

Flask normally runs in single-threaded mode and can only handle one request at a time meaning that any parallel requests should wait until they can be handled.

In order to solve this problem, you only need to put threaded=True in your script and this will result in your application handling each request on a different thread.

I attach here in the following two sample Python scripts that should do the job:

main.py

# main.py

from flask import Flask, render_template, Response
from camera import VideoCamera

app = Flask("AppName")

@app.route('/')
def index():
    return render_template('index.html')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host ="0.0.0.0", port=33, threaded=True)

camera.py

# camera.py

import numpy as np
import cv2
import time 

class VideoCamera(object):

    def __init__(self):
        self.video = cv2.VideoCapture("yourVideo.mp4")

    def __del__(self):
        self.video.release()

    def get_frame(self):

        success, image = self.video.read()                 

        # Image readed by OpenCV is RAW
        # we encode it to JPEG in order to use Motion JPEG for VideoStream after

        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()
Employee
  • 3,109
  • 5
  • 31
  • 50
  • i can use flask, but the problem is- with multi threading there is an increase CPU usage for every new thread. And if the stream is accessed by ,let's say, 100 users simultaneously, then the application will crash. – Madhav Agarwal Sep 27 '18 at 09:38
  • What is the `--frame\r\n` on the line with `yield` please? – Mark Setchell Sep 27 '18 at 13:12