Мне не удается передать поток с одной машины на другую, чтобы я мог отобразить поток на веб-странице с помощью фляги - PullRequest
1 голос
/ 18 апреля 2019

Я хочу захватывать видео в одном raspPi, передавать его с помощью сокетов на другой raspberry (или другой компьютер с python), чтобы оно могло отображаться на веб-странице с помощью flask

Код клиента: (он был протестированЯ могу использовать его для отображения с vlc на рабочем столе сервера)

import io
import socket
import struct
import time
import picamera


# create socket and bind host
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('192.168.1.205', 8000))
connection = client_socket.makefile('wb')

try:
    with picamera.PiCamera() as camera:
        camera.resolution = (320, 240)      # pi camera resolution
        camera.framerate = 15               # 15 frames/sec
        time.sleep(2)                       # give 2 secs for camera to initilize
        start = time.time()
        stream = io.BytesIO()

        # send jpeg format video stream
        for foo in camera.capture_continuous(stream, 'jpeg', use_video_port = True):
            connection.write(struct.pack('<L', stream.tell()))
            connection.flush()
            stream.seek(0)
            connection.write(stream.read())
            if time.time() - start > 600:
                break
            stream.seek(0)
            stream.truncate()
    connection.write(struct.pack('<L', 0))
finally:
    connection.close()
    client_socket.close()

Код сервера: (camerarece.py)

import time
import io
import threading
import picamera
import numpy as np

import socket
import datetime

class Camera2(object):
    try:
        thread = None  # background thread that reads frames from camera
        frame = None  # current frame is stored here by background thread
        last_access = 0  # time of last client access to the camera
        host = "192.168.1.205"
        port = 8000
        server_socket = socket.socket()
        server_socket.bind((host, port))
        server_socket.listen(0)
        connection, client_address = server_socket.accept()
        connection = connection.makefile('rb')
        host_name = socket.gethostname()
        host_ip = socket.gethostbyname(self.host_name)
    except Exception as e:
        print(e)
    def initialize(self):
        if Camera.thread is None:
            # start background frame thread
            Camera.thread = threading.Thread(target=self._thread)
            Camera.thread.start()

            # wait until frames start to be available
            while self.frame is None:
                time.sleep(0)

    def get_frame(self):
        Camera.last_access = time.time()
        self.initialize()
        return self.frame

    @classmethod
    def _thread(cls):



            #stream = io.BytesIO()
            try:

                #self.streaming()
                stream_bytes = b' '
                cls.frame = connection.read(1024)

                cls.thread = None
            except Exception as e:
                print(e)

Предыдущий файл вызывается следующим основным файломПоток полученного канала на веб-страницу фляги:

from flask import Flask, render_template, Response
from camerarece import Camera2 (the previous block of code I posted)

app = Flask(__name__)

@app.route('/')
def index():
    """Video streaming home page."""
    return render_template('index.html')


def gen2():
    """Video streaming generator function."""
    while True:
        frame = Camera2.get_frame()
        #frame = cls.frame
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')        



@app.route('/input_feed')
def input_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen2(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='192.168.1.205', port =5000, debug=True, threaded=True)

Мое личное предположение состоит в том, что я совершенно не могу правильно преобразовать поток сокетов во что-то, что можно использовать в фляге.

Спасибо за помощь, я понимаю,Я бросаю иглу в стоге сена своего рода ситуации.

...