Python Forum
Return Frame as well as JSON response using same API in Flask Python Ask - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Web Scraping & Web Development (https://python-forum.io/forum-13.html)
+--- Thread: Return Frame as well as JSON response using same API in Flask Python Ask (/thread-26723.html)



Return Frame as well as JSON response using same API in Flask Python Ask - jenkins43 - May-11-2020

Using mentioned below code I am trying to return video feed as well as some JSON data in response which will help me further in displaying the data in browser for a particular frame, but from
success, frame = cap.read() 
I am not able to fetch data from
variable success
and share the data with API in which I am getting streamed data,

from flask import Flask, render_template, Response
import cv2

app = Flask(__name__)

# list of camera accesses
cameras = [
 "rtsp://username:[email protected]_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp",
 "rtsp://username:[email protected]_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp", 
...
  ]


def find_camera(list_id):
    return cameras[int(list_id)]


def gen_frames(camera_id):
    cam = find_camera(camera_id)  # return the camera access link with credentials. Assume 0?
    # cam = cameras[int(id)]
    cap = cv2.VideoCapture(cam)  # capture the video from the live feed

    while True:

        # # Capture frame-by-frame. Return boolean(True=frame read correctly. )
        success, frame = cap.read()  # read the camera frame
        if not success:
            break
        else:
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')  # concat frame one by one and show result


@app.route('/video_feed/<string:list_id>/', methods=["GET"])
def video_feed(list_id):
    return Response(gen_frames(list_id),
                    mimetype='multipart/x-mixed-replace; boundary=frame')


@app.route('/', methods=["GET"])
def index():
    return render_template('index.html', camera_list=len(cameras), camera=cameras)


if __name__ == '__main__':
    app.run()
Suggestions will be really helpful