This is my code snippet that sends data over ethernet from one PC to another which is working fine.
JavaScript
x
9
1
import cv2, socket, pickle
2
import numpy as np
3
while True:
4
ret, photo = cap.read()
5
ret, buffer = cv2.imencode(".jpg",photo, [int(cv2.IMWRITE_JPEG_QUALITY),30])
6
x_as_bytes = pickle.dumps(buffer)
7
socket.sendto((x_as_bytes),(server_ip,server_port))
8
9
At the receiver end, I am not able to decode it. It says:
JavaScript
1
5
1
Traceback (most recent call last):
2
File "receive.py", line 12, in <module>
3
data=pickle.loads(data)
4
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
5
This is the snippet at the receiver end
JavaScript
1
12
12
1
while True:
2
x=s.recvfrom(1000000)
3
clientip = x[1][0]
4
data=x[0]
5
print(data)
6
data=pickle.loads(data) #ERROR IN THIS LINE
7
print(type(data))
8
data = cv2.imdecode(data, cv2.IMREAD_COLOR)
9
cv2.imshow('server', data)
10
if cv2.waitKey(10) == 13:
11
break
12
Advertisement
Answer
Why are you even pickling the data? You can send binary data via UDP anyway:
JavaScript
1
9
1
# Synthetic image
2
im = np.random.randint(0, 256,(480, 640, 3), dtype=np.uint8)
3
4
# JPEG encode
5
ret, buffer = cv2.imencode(".jpg", im, [int(cv2.IMWRITE_JPEG_QUALITY),30])
6
7
# Send
8
socket.sendto(buffer.tobytes(), (server_ip,server_port))
9
Then at the receiving end:
JavaScript
1
3
1
JPEG = s.recvfrom(1000000)
2
im = cv2.imdecode(np.frombuffer(JPEG, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
3