edge_Equipment/蓝牙速率测试/main_bt.py

97 lines
2.8 KiB
Python

import bluetooth
import cv2
import json
import time
from rknnpool import rknnPoolExecutor
# 图像处理函数,实际应用过程中需要自行修改
from func import myFunc
# 蓝牙目标设备的MAC地址
TARGET_ADDRESS = "0C:B7:89:58:8E:6E" # 替换为目标设备的蓝牙地址
channel=15
cap = cv2.VideoCapture(40)
modelPath = "./rknnModel/yolov5s_relu_tk2_RK3588_i8.rknn"
TPEs = 3
pool = rknnPoolExecutor(
rknnModel=modelPath,
TPEs=TPEs,
func=myFunc)
# 初始化异步所需要的帧
if (cap.isOpened()):
for i in range(TPEs + 1):
ret, frame = cap.read()
if not ret:
cap.release()
del pool
exit(-1)
pool.put(frame)
frames, loopTime, initTime = 0, time.time(), time.time()
def send_data_via_bluetooth(sock, data):
try:
# 将 JSON 数据编码为 bytes
sock.send(data.encode('utf-8'))
print("Data sent via Bluetooth:", data)
except Exception as e:
print("Error sending Bluetooth data:", e)
def main():
# 创建蓝牙套接字
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
try:
# 连接到目标设备
sock.connect((TARGET_ADDRESS, channel)) # RFCOMM 端口通常为 1
print("Connected to Bluetooth device:", TARGET_ADDRESS)
while (cap.isOpened()):
global frames, loopTime
frames += 1
ret, frame = cap.read()
if not ret:
break
pool.put(frame)
result, flag = pool.get()
if flag == False:
break
if result:
img, boxes, classes, scores = result
if boxes is not None:
detection_info = []
for box, cls, score in zip(boxes, classes, scores):
detection_info.append({
"class": int(cls),
"score": float(score),
"box": [int(coord) for coord in box]
})
json_data = json.dumps(detection_info)
# 通过蓝牙发送数据
send_data_via_bluetooth(sock, json_data)
#cv2.imshow('test', img)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# break
# if frames % 30 == 0:
# print("30帧平均帧率:\t", 30 / (time.time() - loopTime), "帧")
# loopTime = time.time()
# print("总平均帧率\t", frames / (time.time() - initTime))
except Exception as e:
print("Failed to connect or communicate:", e)
finally:
# 释放资源
cap.release()
#cv2.destroyAllWindows()
pool.release()
sock.close()
if __name__ == "__main__":
main()