python - 如何在 Python 中使用 tcp 套接字发送和接收网络摄像头流?

标签 python sockets opencv raspberry-pi3 socketserver

我正在尝试重新创建 this project .我有一个服务器(我的电脑)和一个客户端(我的树莓派)。我所做的与原始项目不同的是,我正在尝试使用简单的网络摄像头而不是树莓派相机将图像从我的 rpi 流式传输到服务器。我知道我必须:

  1. 从相机获取 opencv 图像帧。
  2. 将帧(它是一个 numpy 数组)转换为字节。
  3. 将字节从客户端传输到服务器。
  4. 将字节转换回帧并查看。

示例将不胜感激。

self_driver.py

import SocketServer
import threading
import numpy as np
import cv2
import sys


ultrasonic_data = None

#BaseRequestHandler is used to process incoming requests
class UltrasonicHandler(SocketServer.BaseRequestHandler):

    data = " "

    def handle(self):

        while self.data:
            self.data = self.request.recv(1024)
            ultrasonic_data = float(self.data.split('.')[0])
            print(ultrasonic_data)


#VideoStreamHandler uses streams which are file-like objects for communication
class VideoStreamHandler(SocketServer.StreamRequestHandler):

    def handle(self):
        stream_bytes = b''

        try:
            stream_bytes += self.rfile.read(1024)
            image = np.frombuffer(stream_bytes, dtype="B")
            print(image.shape)
            cv2.imshow('F', image)
            cv2.waitKey(0)

        finally:
            cv2.destroyAllWindows()
            sys.exit()


class Self_Driver_Server:

    def __init__(self, host, portUS, portCam):
        self.host = host
        self.portUS = portUS
        self.portCam = portCam

    def startUltrasonicServer(self):
        # Create the Ultrasonic server, binding to localhost on port 50001
        server = SocketServer.TCPServer((self.host, self.portUS), UltrasonicHandler)
        server.serve_forever()

    def startVideoServer(self):
        # Create the video server, binding to localhost on port 50002
        server = SocketServer.TCPServer((self.host, self.portCam), VideoStreamHandler)
        server.serve_forever()

    def start(self):
        ultrasonic_thread = threading.Thread(target=self.startUltrasonicServer)
        ultrasonic_thread.daemon = True
        ultrasonic_thread.start()
        self.startVideoServer()


if __name__ == "__main__":

    #From SocketServer documentation
    HOST, PORTUS, PORTCAM = '192.168.0.18', 50001, 50002
    sdc = Self_Driver_Server(HOST, PORTUS, PORTCAM)

    sdc.start()

video_client.py

import socket
import time
import cv2


client_sock = socket.socket()
client_sock.connect(('192.168.0.18', 50002))
#We are going to 'write' to a file in 'binary' mode
conn = client_sock.makefile('wb')

try:
    cap = cv2.VideoCapture(0)
    cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH,320)
    cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT,240)

    start = time.time()

    while(cap.isOpened()):
        conn.flush()
        ret, frame = cap.read()
        byteImage = frame.tobytes()
        conn.write(byteImage)


finally:
    finish = time.time()
    cap.release()
    client_sock.close()
    conn.close()

最佳答案

您不能只将每个接收到的 1-1024 字节的缓冲区显示为图像;您必须将它们连接起来,并且仅在缓冲区完成时显示图像。

如果您在带外知道您的图像将是固定数量的字节,您可以这样做:

IMAGE_SIZE = 320*240*3

def handle(self):
    stream_bytes = b''

    try:
        stream_bytes += self.rfile.read(1024)
        while len(stream_bytes) >= IMAGE_SIZE:
            image = np.frombuffer(stream_bytes[:IMAGE_SIZE], dtype="B")
            stream_bytes = stream_bytes[IMAGE_SIZE:]
            print(image.shape)
            cv2.imshow('F', image)
            cv2.waitKey(0)
    finally:
        cv2.destroyAllWindows()
        sys.exit()

如果您不知道这一点,则必须添加某种成帧协议(protocol),例如在每个帧之前将帧大小作为 uint32 发送,这样服务器就可以知道每个帧要接收多少字节。


接下来,如果您只是发送原始字节,没有任何 dtype 或 shape 或顺序信息,您需要将 dtype 和 shape 信息嵌入到服务器中。如果您知道它应该是特定形状的 C 顺序字节,您可以手动执行此操作:

image = np.frombuffer(stream_bytes, dtype="B").reshape(320, 240, 3)

…但如果没有,您也必须将该信息作为框架协议(protocol)的一部分发送。

或者,您可以发送缓冲区的 pickle.dumps 并在另一侧发送 pickle.loads,或者 np.saveBytesIOnp.load 结果。无论哪种方式,它都包括 dtype、shape、order 和 stride 信息以及原始字节,因此您不必担心。


下一个问题是您在显示一张图像后立即退出。那真的是你想要的吗?如果不是……就不要那样做。


但这又引发了另一个问题。您真的要用那个 cv.waitKey 来阻止整个服务器吗?您的客户正在捕捉图像并尽可能快地发送它们;当然,您要么想让服务器在它们到达时立即显示它们,要么更改设计以便客户端仅按需发送帧。否则,您只会得到一堆几乎相同的帧,然后是一个多秒长的间隔,同时客户端被阻塞等待您耗尽缓冲区,然后重复。

关于python - 如何在 Python 中使用 tcp 套接字发送和接收网络摄像头流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51921631/

相关文章:

Python 似乎将实例属性视为类属性

sockets - 详解http保活机制

c - socket编程报错10054

scala - 如何在 Scala 中使用来自 SBT(简单构建工具)的 JavaCV?

python - asyncio as_yielded 来自异步生成器

python - c9.io错误: You don't have permission to access that port

python - 如何用gensim过滤掉语料库中tf-idf低的词?

c - 套接字错误 : connection refused - what am I doing wrong?

c++ - opencv ubuntu 12.04 Cmake错误: Source directory does not appear to contain CmakeLists. txt

opencv - 从conda-forge channel 安装带有conda的OpenCV,即使网页上显示4.11,也可以得到3.4.2版