【发布时间】:2019-08-08 20:40:42
【问题描述】:
我有一个客户端-服务器程序,其中树莓派有客户端,PC 有服务器。我想将 pi 捕获的图像发送到服务器并希望在那里处理它。代码如下。 客户端:
import io
import socket
import struct
from PIL import Image
s = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
s.connect(('ip', 12345))
connection = s.makefile('wb')
try:
camera = picamera.PiCamera()
camera.resolution = (640, 480)
camera.start_preview()
time.sleep(2)
stream = io.BytesIO()
camera.capture(stream , format='jpeg')
connection.write(struct.pack('<L', stream.tell()))
connection.flush()
stream.seek(0)
connection.write(stream.read())
stream.seek(0)
stream.truncate()
finally:
camera.stop_preview()
connection.close()
client_socket.close()
服务器:
import io
import socket
import struct
from PIL import Image
s = socket.socket()
host = '' #ip of raspberry pi
port = 12345
s.bind((host, port))
s.listen(5)
connection = s.accept()[0].makefile('rb')
try:
image_len = struct.unpack('<L',connection.read(struct.calcsize('<L')))[0]
image_stream = io.BytesIO()
image_stream.write(connection.read(image_len))
image_stream.seek(0)
image = Image.open(image_stream)
image.show()
print('Image is verified')
finally:
connection.close()
s.close()
执行此程序时,会出现错误说明:
Traceback (most recent call last):
File "server.py", line 24, in <module>
image = Image.open(image_stream)
File "C:\Users\USER\AppData\Local\conda\conda\envs\cvv\lib\site-packages\PIL\I
mage.py", line 2687, in open
% (filename if filename else fp))
OSError:
cannot identify image file <_io.BytesIO object at 0x000000D6
请帮帮我。
【问题讨论】:
-
在 image_stream 中找不到图像。您能否在尝试保存之前确认流是有效的?
-
我认为 image_stream 存在。当我尝试打印 image_stream 时,它显示 io.bytesio 对象存在于某个 headecimal 值。
标签: python python-2.7 image-processing tcp raspberry-pi3