Files
lora_plug/test_send.py

92 lines
2.4 KiB
Python
Raw Permalink Normal View History

2025-02-19 16:09:44 +08:00
import serial_module
import cv2
import time
2025-02-19 19:57:21 +08:00
import threading
# 全局变量
frame = None
frame_lock = threading.Lock()
thread_started = False
# 摄像头读取线程
def cap_thread():
global frame, thread_started
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error: Could not open camera.")
return
# 标记线程已启动
thread_started = True
while True:
time_now = time.time()
ret, temp_frame = cap.read()
if ret:
with frame_lock:
# 在图像上打印时间
# print(f"Time: {time_now:.2f}")
cv2.putText(temp_frame, f"{time_now:.2f}", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 4)
frame = temp_frame
else:
print("Error: Failed to read frame from camera.")
time.sleep(0.1) # 短暂休眠,避免频繁尝试读取
2025-02-19 16:09:44 +08:00
# 初始化串口
serial_module.init("/dev/ttyUSB0")
2025-02-19 19:57:21 +08:00
# 启动摄像头读取线程
threading.Thread(target=cap_thread, daemon=True).start()
2025-02-19 16:09:44 +08:00
2025-02-19 19:57:21 +08:00
# 等待子线程初始化完成
while not thread_started:
time.sleep(0.1)
# 主线程处理逻辑
# for _ in range(100):
while True:
2025-02-19 16:09:44 +08:00
time_via = time.time()
2025-02-19 19:57:21 +08:00
# 检查帧是否可用
with frame_lock:
if frame is None:
# print('frame is None')
time.sleep(0.1) # 短暂休眠,避免频繁检测
continue
# 调整帧大小
try:
frame_resized = cv2.resize(frame, (224, 224))
except Exception as e:
print(f"Error resizing frame: {e}")
continue
# 编码帧为 JPEG 格式
try:
frame_jpg = cv2.imencode('.jpg', frame_resized, [int(cv2.IMWRITE_JPEG_QUALITY), 50])[1].tobytes()
except Exception as e:
print(f"Error encoding frame: {e}")
continue
# 打印帧大小并发送数据
print(f"Frame size: {len(frame_jpg)} bytes")
2025-02-19 16:09:44 +08:00
serial_module.send(frame_jpg)
2025-02-19 19:57:21 +08:00
# 保存帧到文件(用于调试)
try:
cv2.imwrite('test_send.jpg', frame_resized)
except Exception as e:
print(f"Error saving frame: {e}")
# 打印时间消耗
print(f"Time taken: {time.time() - time_via:.3f} seconds")
# 控制循环频率
# time.sleep(4)
2025-02-19 16:09:44 +08:00
2025-02-19 19:57:21 +08:00
# 按 'q' 键退出
2025-02-19 16:09:44 +08:00
if cv2.waitKey(1) & 0xFF == ord('q'):
break
2025-02-19 19:57:21 +08:00
# 释放资源
cv2.destroyAllWindows()