我希望制作一个流媒体播放器,能够在我的局域网内从一台电脑传输视频到另一台电脑(或同一台电脑)。为了尽可能地节省带宽,我需要使用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
以下是我的当前客户端代码(发送者):
import cv2
import numpy as np
import socket
import _pickle
from cv2 import *
host = "192.168.1.196"
port = 25565
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # declares s object with two parameters
s.connect((host, port)) # connects to the host & port
cap = cv2.VideoCapture(1)
cv2.cv.CV_FOURCC('H','2','6','4')
while cap.isOpened(): # while camera is being used
ret, frame = cap.read() # reads each frame from webcam
cv2.imshow("client", frame)
if ret:
encoded = _pickle.dumps(cv2.imencode("fourcc", frame)[1]) # encoding each frame, instead of sending live video it is sending pictures one by one
s.sendall(encoded)
if cv2.waitKey(1) & 0xFF == ord("q"): # wait until key was pressed once and
break
cap.release()
cv2.destroyAllWindows()
我只需要一些关于如何对视频进行H264编码和解码的帮助。