客户端(桌面)上的此代码未显示从服务器端(树莓派)发送的视频流。当我打印接收到的帧时,会得到类似
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)