This is my code snippet that sends data over ethernet from one PC to another which is working fine.

import cv2, socket, pickle
import numpy as np
while True:
    ret, photo = cap.read()
    ret, buffer = cv2.imencode(".jpg",photo, [int(cv2.IMWRITE_JPEG_QUALITY),30])
    x_as_bytes = pickle.dumps(buffer)
    socket.sendto((x_as_bytes),(server_ip,server_port))

At the receiver end, I am not able to decode it. It says:

Traceback (most recent call last):
    File "receive.py", line 12, in <module>
       data=pickle.loads(data)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

This is the snippet at the receiver end

while True:
    x=s.recvfrom(1000000)
    clientip = x[1][0]
    data=x[0]
    print(data)
    data=pickle.loads(data) #ERROR IN THIS LINE
    print(type(data))
    data = cv2.imdecode(data, cv2.IMREAD_COLOR)
    cv2.imshow('server', data)
    if cv2.waitKey(10) == 13:
        break

推荐答案

Why are you even pickling the data? You can send binary data via UDP anyway:

# Synthetic image
im = np.random.randint(0, 256,(480, 640, 3), dtype=np.uint8)

# JPEG encode
ret, buffer = cv2.imencode(".jpg", im, [int(cv2.IMWRITE_JPEG_QUALITY),30])

# Send
socket.sendto(buffer.tobytes(), (server_ip,server_port))

Then at the receiving end:

JPEG = s.recvfrom(1000000)
im = cv2.imdecode(np.frombuffer(JPEG, dtype=np.uint8), cv2.IMREAD_UNCHANGED)

Python相关问答推荐

为什么'if x is None:pass'比'x is None'单独使用更快?

Python pint将1/华氏度转换为1/摄氏度°°

对数据帧进行分组,并按组间等概率抽样n行

将数字数组添加到Pandas DataFrame的单元格依赖于初始化

如何在Quarto中的标题页之前创建序言页

为什么按下按钮后屏幕的 colored颜色 保持不变?

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名

Pandas 删除只有一种类型的值的行,重复或不重复

函数()参数';代码';必须是代码而不是字符串

按列表分组到新列中

如何在保持sibling 姐妹美汤的同时插入和删除标签?

使用HingeEmbeddingLoss()函数进行二进制分类时出现问题

将代码推送到服务器时,连接WebSocket时出错

.yml不会在专用环境中安装来自.requirements.txt的软件包

Python渐进式打字

一种获取所有相关列的极点数据帧绝对最大值的毕达式方法

如何才能将文本文件分成多列,但仅限于特定的行?

如何编写拆分和 Select 每个PANAS列中的第一个元素的Python函数

为什么我不能在Sphinxcontrib-HttpExample中使用python来换行JSON属性?

在多级列中,对特定较低级别的类别重新排序