Python Opencv和Sockets流式视频编码在h264中

2024-04-29 19:26:31 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我尝试在我的局域网上制作一个从一台计算机到另一台(或者现在是同一台)的流媒体。我需要它使用尽可能少的带宽,所以我试图在h264编码。我做这件事有困难,我真的不知道从哪里开始。现在它是用jpg编码的,它正在逐帧发送。但是,我知道,这是非常低效的,它消耗了大量的带宽。这是我当前的接收代码。在

import cv2
import socket
import _pickle
import time

host = "192.168.1.196"
port = 25565
boo = True

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # declares s object with two parameters
s.bind((host, port)) # tells my socket object to connect to this host & port "binds it to it"
s.listen(10) # tells the socket how much data it will be receiving.

conn, addr = s.accept()
buf = ''
while boo:
        pictures = conn.recv(128000) # creates a pictures variable that receives the pictures with a max amount of 128000 data it can receive
        decoded = _pickle.loads(pictures) # decodes the pictures
        frame = cv2.imdecode(decoded, cv2.IMREAD_COLOR) # translates decoded into frames that we can see!
        cv2.imshow("recv", frame)
        if cv2.waitKey(1) & 0xFF == ord("q"):  # wait until q key was pressed once and
            break

这是我当前的客户代码(发件人):

^{pr2}$

我只需要一些帮助,如何编码和解码的视频在h264。在


Tags: theto代码importhost编码portit
1条回答
网友
1楼 · 发布于 2024-04-29 19:26:31

您可以使用^{}和带有base64字符串编码/解码的publish/subscribe模式来实现这一点。在服务器端,我们的想法是:

  • 从摄影机流获取帧
  • 使用cv2.imencode从内存缓冲区读取图像
  • 使用base64将ndarray转换为{},并通过套接字发送

在客户端,我们只需反向执行此过程:

  • 从套接字读取图像字符串
  • 使用base64将str转换为{}
  • 使用np.frombuffer+cv2.imdecodebytes转换为{}

这个方法不应该使用太多带宽,因为它只在套接字上发送字符串。在


服务器

import base64
import cv2
import zmq

context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.connect('tcp://localhost:7777')

camera = cv2.VideoCapture(0)

while True:
    try:
        ret, frame = camera.read()
        frame = cv2.resize(frame, (640, 480))
        encoded, buf = cv2.imencode('.jpg', frame)
        image = base64.b64encode(buf)
        socket.send(image)
    except KeyboardInterrupt:
        camera.release()
        cv2.destroyAllWindows()
        break

客户

^{pr2}$

相关问题 更多 >