gpt4 book ai didi

python - 使用 OpenCV (Python) 从 Flask 服务器读取 MJPEG 流

转载 作者:太空狗 更新时间:2023-10-30 01:31:48 24 4
gpt4 key购买 nike

我正在使用 Flask 和 flask-restful 生成 MJPEG 流。由于某些原因,我想在我使用 OpenCV(3) 的另一个 Python 程序中捕捉这个流。问题是请求的第一帧很好。另一方面,请求的第二帧(延迟后)未正确接收,并抛出错误:

[mpjpeg @ 0000017a86f524a0] Expected boundary '--' not found, instead found a line of 82 bytes

多次。

我相信这是因为框架的边界是手动设置的。我将把有问题的代码放在下面。

MJPEG 流生成:

## Controller for the streaming of content.
class StreamContent(Resource):
@classmethod
def setVis(self, vis):
self.savedVis = vis

def get(self):
return Response(gen(VideoCamera(self.savedVis)),
mimetype='multipart/x-mixed-replace; boundary=frame')


## Generate a new VideoCamera and stream the retrieved frames.
def gen(camera):
frame = camera.getFrame()
while frame != None:
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
time.sleep(0.07)
frame = camera.getFrame()

## Allows for the reading of video frames.
class VideoCamera(object):
def __init__(self, vis):
#object we retrieve the frame from.
self.vis = vis

## Get the current frame.
def getFrame(self):
image = self.vis.mat_frame_with_overlay
# We are using Motion JPEG, but OpenCV defaults to capture raw images,
# so we must encode it into JPEG in order to correctly display the
# video/image stream.
ret, jpeg = cv2.imencode('.jpg', image)
return jpeg.tobytes()

MJPEG 流检索:

"""
Get a single frame from the camera.
"""
class Image(Resource):
def get(self):
camera = VideoCamera()
return Response(camera.getSingleFrame(), mimetype='image/jpeg')

"""
Contains methods for retrieving video information from a source.
"""
class VideoCamera(object):
def __del__(self):
self.video.release()

@classmethod
def setVideo(self, video):
self.video = video

## Get the current frame.
def getSingleFrame(self):
self.startVideoFromSource(self.video)
ret, image = self.video.read()
time.sleep(0.5)
ret, image = self.video.read()
# We are using Motion JPEG, but OpenCV defaults to capture raw images,
# so we must encode it into JPEG in order to correctly display the
# video/image stream.
ret, jpeg = cv2.imencode('.jpg', image)
self.stopVideo()
return jpeg.tobytes()

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

最佳答案

更改帧生成器对我有用:

yield (b'--frame\r\n'
b'Content-Type:image/jpeg\r\n'
b'Content-Length: ' + f"{len(frame)}".encode() + b'\r\n'
b'\r\n' + frame + b'\r\n')

关于python - 使用 OpenCV (Python) 从 Flask 服务器读取 MJPEG 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48909132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com