【问题标题】:How to display an encoded OpenCV image on a Flask web server?如何在 Flask Web 服务器上显示编码的 OpenCV 图像?
【发布时间】:2019-04-24 04:25:47
【问题描述】:

我有一个客户端,它从相机中提取帧,然后将它们压缩并存储在 JSON 对象中以发送到 Flask 服务器。我需要在 Flask 界面上显示所述帧图像。我当前的尝试没有返回错误,但它只是打印一个 np 数组而不是显示实际图像。

client.py

class Camera(object):
    def __init__(self, mode, addr, id):
        self.id = id
        self.video = None
        if(mode == "file" and type(addr) == type("hi")):
            self.video = cv2.VideoCapture(addr)
        elif(mode == "live" and type(addr) == type(0)):
            self.video = cv2.VideoCapture(addr)
        else:
            print("ERROR: Camera class given either an incorrect mode or an address of the wrong type.")

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

    def get_cam_id(self):
        return self.id

    def get_frame(self):
        ret, frame = self.video.read()
        if(ret == True):
            return frame
        else:
            return None

    def norm_frame(self, frame):
        frame = cv2.resize(frame, None, fx=0.6, fy=0.6)
        return frame

    def package(self, frame):
                frame = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 70])[1].tolist()
                frame = json.dumps(frame)
                return frame

test_config 路由在applications.py

@application.route('/test_config', methods = ['GET', 'POST'])
def test2():
    var = input('Enter ID: ')
    print(FEEDS[var])
    frame = FEEDS[var].package(FEEDS[var].norm_frame(FEEDS[var].get_frame()))
    print(frame)


""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Attempt
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    #frame = json.loads(frame)
    #frame = np.asarray(frame, np.uint8)
    #frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)
    #return frame
    return "Frame will display here eventually!"

有一个/test_input 路由允许用户输入有关摄像机的信息。所述信息用于在client.py 中创建相机对象。对象存储在带有 ID 键的 applications.py 的字典中,在输入 test_config 时将确定显示哪个帧。我遇到的问题是在输入 Camera 对象的键后显示图像。

【问题讨论】:

  • 要发送图像(或任何文件),您必须发送标头,其中包含您发送的文件类型的信息。通常它会发送带有它是 HTML 文件的信息的标题。
  • 你应该使用type(addr) == type("hi") 而不是isinstance(addr, str) - 它是首选且更具可读性。与type(addr) == type(0) 相同 - isinstance(addr, int)
  • 如果我没有图像文件名,我将如何使用链接答案中的方法?抱歉,我只是不确定如何将该解决方案应用于此问题。
  • 使用任何文本作为名称——随机文本、“hello-world.jpg”、当前日期和时间等。HTTP 协议可能只需要它来正确发送数据。但是使用可能需要它以默认名称将图像保存在磁盘上。保存图像时无需更改名称会更容易。

标签: python json opencv flask


【解决方案1】:

我找到了解决方案。谢谢@furas 的帮助。

r = requests.get('http://127.0.0.1:8080/get_frame').content
frame = json.loads(r)
frame = np.asarray(frame, np.uint8)
frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)
r, jpg = cv2.imencode('.jpg', frame)
return Response(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n', mimetype='multipart/x-mixed-replace; boundary=frame')

【讨论】:

    猜你喜欢
    • 2019-07-24
    • 1970-01-01
    • 2018-01-22
    • 2014-02-07
    • 2011-10-12
    • 2012-10-06
    • 2021-11-18
    • 1970-01-01
    • 2021-12-26
    相关资源
    最近更新 更多