我是Python的新手。我正在尝试从我的Raspberry Pi相机捕获视频流,对其进行一些处理,然后将生成的图像流式传输到另一台计算机。我需要帮助将后处理后的图像转换回可以通过套接字连接发送的流。这是我的代码:
import io
import socket
import struct
import time
import picamera
import cv2
import numpy as np
client_socket = socket.socket()
client_socket.connect(('192.168.0.131', 8000))
connection = client_socket.makefile('wb')
try:
with picamera.PiCamera() as camera:
camera.resolution = (640, 480)
camera.framerate = 30
time.sleep(2)
start = time.time()
stream = io.BytesIO()
print(type(stream))
# Use the video-port for captures...
for foo in camera.capture_continuous(stream, 'jpeg', use_video_port=True):
data = np.fromstring(stream.getvalue(), dtype=np.uint8)
image=cv2.imdecode(data,1)
height,width,channels=image.shape
midheight=int(height/2)
midwidth=int(width/2)
cv2.line(image,(0,midheight),(width,midheight),(0,255,0),2)
cv2.line(image,(midwidth,0),(midwidth,height),(0,255,0),2)
stream=io.BytesIO(image)
#print(type(stream))
connection.write(struct.pack('<L', stream.tell()))
connection.flush()
stream.seek(0)
connection.write(stream.read())
if time.time() - start > 30:
break
stream.seek(0)
stream.truncate()
connection.write(struct.pack('<L', 0))
finally:
connection.close()
client_socket.close()
代码不断断开与客户端的连接。如果我不尝试将处理后的图像写入流,则连接稳定,代码按预期工作。 任何帮助都会很棒。