Как получить видеопоток через сокет от raspberry pi на мой рабочий стол? - PullRequest
0 голосов
/ 16 апреля 2019

Этот код на стороне клиента (рабочий стол) не показывает видеопоток, который отправляется со стороны сервера (малина).и когда я печатаю полученные кадры, я получаю что-то вроде

image/jpeg\r\nContent-Length: 480\r\n\r\n\xff\xd8;;<=<>=>==;:<;;;;;<;==<=;;;;;==<<<>?<<<<;;<<<=<;<;=;<<<:;;<;;;<==;<<<;><===<;;;;;;:<<:;;;<;:;;;;<<:::;;;<;=<::;;;;;<:; ......

Код, который я пробовал:

import cv2
import numpy as np
import os
import urllib.request
import socket               

# Open stream
stream = urllib.request.urlopen('http://192.168.1.101:8000/stream.mjpg')

#iniciate id counter
id = 0

# Initialize and start realtime video capture

bytes = b''
count = 0
while True:
bytes += stream.read(100000)
print(bytes)
#if bytes.startswith(b'\xff\xd8'):
a = bytes.find(b'\xff\xd8')
b = bytes.find(b'\xff\xd9')
if a != -1 and b != -1 and b > a:
    jpg = bytes[a:b+2]
    bytes = bytes[b+2:]
    img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), 
cv2.IMREAD_GRAYSCALE)

    print (a,b)
    #cv2.imshow('camera',img) 
    bytes = []

k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video
if k == 27:
    break
count = 1
# Do a bit of cleanup
print("\n [INFO] Exiting Program and cleanup stuff")

cv2.destroyAllWindows()

А вот код насторона Raspberry: сервер и потоковый обработчик: А вот код на стороне Raspberry: сервер и обработчик потоков:

class StreamingOutput(object):

    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition()

    def write(self, buf):
        #if buf.startswith(b'\xff\xd8'):
        # New frame, copy the existing buffer's content and notify all
        # clients it's available
        self.buffer.truncate()
        with self.condition:
        self.frame = self.buffer.getvalue()
        self.condition.notify_all()
        self.buffer.seek(0)
        return self.buffer.write(buf)

class StreamingHandler(server.BaseHTTPRequestHandler):
    output = None
    q1 = None

    def do_GET(self):

        if self.path == '/':
            self.send_response(301)
            self.send_header('Location', '/index.html')
            self.end_headers()
        elif self.path == '/index.html':
            content = PAGE.encode('utf-8')
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.send_header('Content-Length', len(content))
            self.end_headers()
            self.wfile.write(content)
        elif self.path == '/stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; 
            boundary=FRAME')
            self.end_headers()

        try:

            while True:


                if not StreamingHandler.q1.empty():

                    #StreamingHandler.output.condition.wait()
                    qq = StreamingHandler.q1

                    frame = qq.get() 
                    print("got queue item",frame)
                    #cv2.imshow("camera",frame)
                    qq.queue.clear()

                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame))
                    self.end_headers()
                    self.wfile.write(b'\xff\xd8')

                    self.wfile.write(frame)

                    self.wfile.write(b'\xff\xd9')
                    self.wfile.write(b'\r\n')
        except Exception as e:
            logging.warning(
                'Removed streaming client %s: %s',
                self.client_address, str(e))

    else:
        self.send_error(404)
        self.end_headers()

class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer): 
    def __init__(self, address, handler, output, q1):
        handler.output = output
        handler.q1 = q1
        super().__init__(address, handler)
        allow_reuse_address = True
        daemon_threads = True
    def start_server():
        try:
            address = ('', 8000)
            server = StreamingServer(address, StreamingHandler, output)
            server.serve_forever()
        finally:
            print("heloE")
            pass

def start_streaming(q):
    try:
        output = StreamingOutput()    
        address = ('', 8000)
        server = StreamingServer(address, StreamingHandler, output,q)
        server.serve_forever()
        print("server started")
    finally:
        server.serve_stop() 


if __name__ == '__main__':
    start_streaming(q)
...