如何从FlaskAPI(服务器)打开用户/客户端(android、iphone、python)上的摄像头?

iq3niunx  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(400)

我正在flask中开发一个对象检测api,我想从客户端获取一个实时视频流,它可能来自android手机、iphone,或者仅仅来自windows/linux上运行的python脚本。起初,我尝试了以下几点:

def processFrames():
    print('[DEBUG] call cv2.VideoCapture(0) from PID', os.getpid())
    camera = cv2.VideoCapture(0)
    while camera.isOpened():
        ret, frame = camera.read()
        if not ret:
            break
        else:
            frame = DetectObject(frame) 

            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')

@endpoints.route('/RealTime', methods=['GET','POST'])
def RealTime():
    return Response(processFrames(), mimetype='multipart/x-mixed-replace; boundary=frame')

但它不断地给出错误:
[警告:1]全局/tmp/pip-req-build-13uokl4r/opencv/modules/videoio/src/cap_v4l.cpp(890)打开videoio(v4l2:/dev/video0):无法按索引打开相机
我意识到这是因为opencv试图打开服务器上的摄像头。然后我想到了这个解决方案:https://stackoverflow.com/a/59998983/16396308
但我不知道如何从以下方面得到回应:

emit('response_back', stringData)

[编辑]
请提供帮助,因为当我使用上面的解决方案时,通过 Postman 发送了一张图像,这是我在服务器上的:

frame = secure_filename(file.filename)
sbuf = StringIO()
sbuf.write(frame)
b = BytesIO(pybase64.b64decode(frame))
pimg = Image.open(b)

要以文件形式接收图像(目前),但对于一个图像,我会出现以下错误:
binascii.error binascii。
错误:填充不正确
对于不同的图像,我得到以下错误:
pil.unidentifiedimageerror
pil.unidentifiedimageerror:无法识别图像文件<\u io.bytesio对象位于0x7f3d9bbcf5e0>

xtfmy6hx

xtfmy6hx1#

您可以使用socketio获取用户提要,

from flask import Flask, render_template, request
...
@socketio.on('connect', namespace='/web')
def connect_web():
    print('[INFO] Web client connected: {}'.format(request.sid))

@socketio.on('disconnect', namespace='/web')
def disconnect_web():
    print('[INFO] Web client disconnected: {}'.format(request.sid))

@socketio.on('connect', namespace='/cv')
def connect_cv():
    print('[INFO] CV client connected: {}'.format(request.sid))

@socketio.on('disconnect', namespace='/cv')
def disconnect_cv():
    print('[INFO] CV client disconnected: {}'.format(request.sid))

以下是一些有用的链接:
https://towardsdatascience.com/video-streaming-in-web-browsers-with-opencv-flask-93a38846fe00
https://learn.alwaysai.co/build-your-own-video-streaming-server-with-flask-socketio
https://github.com/alwaysai/video-streamer

相关问题