import cv2
import numpy as np
import paho.mqtt.client as mqtt
import json
import base64
SERVER_IP = "iot-06z00h8fcx1brqy.mqtt.iothub.aliyuncs.com" # 服务器IP
SERVER_PORT = 1883 # 端口号
ClientID = "k0slmhwja7J.imageB|securemode=2,signmethod=hmacsha256,timestamp=1706773789996|"
Username = "imageB&k0slmhwja7J"
Password = "149c74c3be3ac8aa4c7576db62f4c391805014af34229ff70fe83a4c910311a2" # 密文
SUB_TOPIC = "/k0slmhwja7J/imageB/user/image" # 订阅
# 定义全局变量
video_writer = None
# MQTT连接回调函数
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT broker")
# 订阅主题
client.subscribe(SUB_TOPIC)
else:
print("Failed to connect, return code %d\n", rc)
# MQTT消息接收回调函数
def on_message(client, userdata, msg):
global video_writer
# 获取Base64编码的图像数据
image_data = json.loads(msg.payload.decode("utf-8"))
image_str = image_data["image"]
# Base64解码
image_bytes = base64.b16decode(image_str)
# 解压缩为图像数据
nparr = np.fromstring(image_bytes, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
# 显示图像
# 添加到视频流
if video_writer is None:
height, width, channels = img.shape
video_writer = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'MJPG'), 0.5, (width, height))#帧率参数(5)
video_writer.write(img)
# 显示视频
cv2.imshow("Video Stream", img)
cv2.waitKey(1)
# 创建MQTT客户端
client = mqtt.Client(ClientID)
client.username_pw_set(Username, Password) # 设置用户名和密码
client.on_connect = on_connect # 设置连接回调函数
client.on_message = on_message # 设置消息接收回调函数
client.connect(SERVER_IP, SERVER_PORT, 60) # 连接MQTT服务器
# 循环等待消息接收
client.loop_forever()
阿里云平台视频订阅代码
于 2024-04-02 14:13:21 首次发布