通过套接字发送numpy数组 [英] Sending numpy arrays via Socket
问题描述
首先,我想做的是: 使用Socket将照片从我的Raspberry Pi发送到笔记本电脑.
First of all, what I want to do: Sending Photos with Socket from my Raspberry Pi to my laptop.
客户:
#!/usr/bin/python
import socket
import cv2
import numpy as np
import pickle
#Upload image
img = cv2.imread('/path/to/image', 0)
#Turn image into numpy-array
arr = np.asarray(img)
#Receiver ip
ip = "XXX.XXX.X.XXX"
#Set up socket and stuff
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#Loop through each array (5 for test)
for each in range(5):
#Encode each array
msg = pickle.dumps(arr[each][0])
#Send msg to ip with port
s.sendto(msg, (ip, 50000))
s.close()
这里发生了什么: 我上传图片,然后将其变成一个Numpy数组.然后,我获取数组的每一行(每个列表),然后用pickle对其进行编码",然后再通过Socket发送.至此一切正常.
What happens here: I upload a picture and then turn it into an Numpy array. Then I take each line of the array (each list) and "encode" it with pickle to send it afterwards via Socket. Everything works fine to this point.
服务器:
#!/usr/bin/python
import socket
import numpy as np
import cPickle as pickle
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", 50000))
while True:
data, addr = s.recvfrom(4096)
conv = pickle.loads(data)
print conv
#print np.fromstring(conv,dtype=int)
s.close()
服务器接收编码后的数据,并将其解码回一个Numpy数组(这就是我想要实现的).
The server receives the encoded data and decodes it back into an Numpy array (that's what I want to achieve).
最后,它应该将数组重新转换为图像,但是由于此时的问题,我什至没有涉及到这一部分.
At the end, it should turn the array back into an image, but I didn't even get to that part, because of the issues I have at this point.
我还尝试过先将数组转换为字符串,然后用pickle对其进行编码,然后将其发送,以便在解码时将其作为一个numpy数组.但这不能很好地工作.
I've also tried to turn the array into a string first, encode it with pickle and then send it so when it gets decoded, it is an numpy array. But that didn't work well.
ValueError:字符串大小必须是元素大小的倍数
无论是链接还是指出我的错误,我都会提供任何帮助,我们将不胜感激. 已经为此工作了好几天,没有发现任何可以帮助我解决此问题的方法.
I would appreciate any kind of help, be it a link or pointing out my mistake. Have been working on this for days and haven't found anything that could help me in this matter.
提前谢谢.
推荐答案
您不需要OpenCV和NumPy.相反,只需直接发送文件的字节即可.如果您拥有Python 3.5,甚至可以使用socket.sendfile()
.
You don't need OpenCV and NumPy for this. Instead, simply send the bytes of the file directly. If you have Python 3.5 you can even use socket.sendfile()
.
有关更多详细信息,请参见:通过Python中的TCP套接字发送文件
For more detail see: Sending a file over TCP sockets in Python
这篇关于通过套接字发送numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!