使用WebSocket将图像作为字节发送JSON [英] Send JSON with image as bytes using WebSocket

查看:642
本文介绍了使用WebSocket将图像作为字节发送JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用WebSocket从cv2.Videocapture发送和接收图像.

I want to send and receive image from cv2.Videocapture using WebSocket.

它可以获取json,但无法解码.

It could get json, but it couldn't decoded.

我们需要可以使用cv2.imshow()打开的结果.

We need result that can be opened using cv2.imshow().

有人帮助我...

这是客户

ret, image_np = cap.read()
        IMAGE_SHAPE = image_np.shape
        encoded_image = base64.b64encode(image_np)
        print(type(encoded_image))
        payload = {
            'from': 'rasp',
            'image': str(encoded_image),
            'shape': IMAGE_SHAPE,
        }

        data = json.dumps(payload)

        try:
            # Send encoded image data.
            await websocket.send(data)

            # receive server message
            received_data = await websocket.recv()
            print('< {}'.format(received_data))

            # image = base64.b64decode(received_data)
            # np_image = np.fromstring(image, dtype=np.uint8)
            # source = np_image.reshape(IMAGE_SHAPE)
            return websocket
        except Exception:
            print('WebSocket send or receive error.')
            exit(1)

这是服务器

async def server_on(websocket, path):
payload = {
    'from': 'image-server',
    # 'result': {
    #     # Default is null.
    #     'isPerson': <bool>,
    #     'centerPoint': <(x, y)>,
    # },
}

data = json.dumps(payload)

try:
    payload = await websocket.recv()
    receive_data = json.loads(payload)
    # At this line doesnt work... 
    decoded_image = base64.b64decode(receive_data['image'])
    image_np = np.fromstring(decoded_image, dtype=np.uint8)
    source = image_np.reshape(receive_data['shape'])


    await websocket.send(data)
except Exception:
    websocket.close()
    return

推荐答案

在您的客户中,我想说您不需要执行额外的操作. 根据您的最新评论,您可能不需要使用:str(encoded_image).

In your Client I would say that you have an extra operation not needed. Based on your latest comment, you might not need to use: str(encoded_image).

您可以尝试使用:base64.encodestring(image_np)它将向您发送回一个字符串容器.

You could try to use: base64.encodestring(image_np) that will send you back a string container.

ret, image_np = cap.read()
        IMAGE_SHAPE = image_np.shape
        encoded_image = base64.encodestring(image_np)
        print(type(encoded_image))
        payload = {
            'from': 'rasp',
            'image': encoded_image.decode('utf-8'),
            'shape': IMAGE_SHAPE,
        }

这篇关于使用WebSocket将图像作为字节发送JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆