通过TCP套接字发送的相机Feed有时会卡住

时间:2019-03-06 13:25:49

标签: python sockets tcp raspberry-pi

我正在使用TCP套接字将Raspberry PI上的摄像头的摄像头馈送至计算机,以将其用于openCV。它运作良好,延迟最小。但是,有时框架会卡住(冻结),并且一段时间后提要返回或openCV窗口崩溃。我到处都看过并尝试了多种方法,但我只是不知道是什么原因造成的。

服务器(PC):

import socket
import struct
import numpy as np
import cv2

host = "192.168.0.12"
portCar = 8010

# Camera socket
camS = socket.socket()
camS.bind((host, portCar))

camS.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

# Listen for camera
camS.listen(0)
print("Waiting for camera connection...")

camCon = camS.accept()[0]
camFile = camCon.makefile("rb")
print("Connection made with camera")

camS.settimeout(0.00001)

numOfBytes = struct.calcsize("<L")

try:
    while(True):
        camS.setblocking(False)

        imageLength = struct.unpack("<L", camFile.read(numOfBytes))[0]    

        if imageLength == 0:
            break

        nparr = np.frombuffer(camFile.read(imageLength), np.uint8)
        frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

        cv2.imshow('RC Car Video stream', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

finally:
    camFile.close()
    camS.close()
    cv2.destroyAllWindows()
    print("Server - Camera connection closed")

客户(PI):

import io
import socket
import struct
import time
import picamera

client_socket = socket.socket()
client_socket.connect(('192.168.0.12', 8010))

client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

connection = client_socket.makefile('wb')

class SplitFrames(object):
    def __init__(self, connection):
        self.connection = connection
        self.stream = io.BytesIO()

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            size = self.stream.tell()
            if size > 0:
                self.connection.write(struct.pack('<L', size))
                self.connection.flush()
                self.stream.seek(0)
                self.connection.write(self.stream.read(size))
                self.stream.seek(0)

        self.stream.write(buf)


try:
    output = SplitFrames(connection)
    with picamera.PiCamera(resolution='VGA', framerate=30) as camera:
        time.sleep(2)
        camera.rotation = 180
        camera.start_recording(output, format='mjpeg')
        camera.wait_recording(2000)
        camera.stop_recording()
        # Write the terminating 0-length to the connection to let the
        # server know we're done
        connection.write(struct.pack('<L', 0))
finally:
    connection.close()
    client_socket.close()
    print("Client - Connection closed")

任何帮助将不胜感激。

0 个答案:

没有答案