python代码实时h264视频tcp发送与接收
时间: 2023-11-29 19:05:09 浏览: 64
发送端代码:
```python
import cv2
import socket
import struct
import pickle
# 创建socket连接
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('127.0.0.1', 8000))
# 加载视频
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
# 将视频帧转成h264编码格式
result, frame = cv2.imencode('.h264', frame)
# 将h264编码的视频帧序列化
data = pickle.dumps(frame)
# 获取序列化后的视频帧大小
size = len(data)
# 将视频帧大小打包成4字节的二进制数据
size_data = struct.pack('i', size)
# 发送视频帧大小和序列化后的视频帧数据
client_socket.sendall(size_data + data)
# 关闭连接
client_socket.close()
```
接收端代码:
```python
import socket
import struct
import pickle
import cv2
# 创建socket连接
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('127.0.0.1', 8000))
server_socket.listen(1)
# 接受客户端连接
conn, addr = server_socket.accept()
while True:
# 接收视频帧大小
size_data = conn.recv(4)
# 如果没有接收到数据,则退出循环
if not size_data:
break
# 将接收到的二进制数据解包成整数,得到视频帧大小
size = struct.unpack('i', size_data)[0]
# 接收视频帧数据
data = b''
while len(data) < size:
packet = conn.recv(size - len(data))
if not packet:
break
data += packet
# 将接收到的视频帧数据反序列化
frame = pickle.loads(data)
# 将h264编码的视频帧解码为BGR格式
frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)
# 显示视频帧
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('q'):
break
# 关闭连接
conn.close()
server_socket.close()
cv2.destroyAllWindows()
```
阅读全文