通过UDP发送腌制数据,UnicodeDecodeError失败了:' ascii'编解码器可以在位置0:序列不在范围内(128)中解释字节0xff

发布于 2025-02-11 19:11:27 字数 920 浏览 3 评论 0原文

这是我的代码片段,它将通过以太网从一台PC发送到另一台PC的数据效果很好。

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

在接收器端,我无法解码它。它说:

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)

这是接收器端的片段

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝梦月影 2025-02-18 19:11:27

您为什么还要腌制数据?无论如何,您都可以通过UDP发送二进制数据:

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

然后在接收端:

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

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文