[简单的警报功能] 核桃派搭配官方usb摄像并控制蓝灯或者......

设备准备:
核桃派开发板一块,官网摄像头一个。
image

image

1. 导入所需的库和模块:

import cv2
import board
from digitalio import DigitalInOut, Direction
from time import sleep
import threading

2. 创建VideoCapture对象并检查摄像头是否成功打开

cap = cv2.VideoCapture(1)
if not cap.isOpened():
     print("无法打开摄像头")
     exit()

3. 初始化LED对象并设置引脚:

 led = DigitalInOut(board.LED)
 led.direction = Direction.OUTPUT

4. 初始化变量和锁:

prev_frame = None
motion_detected = False
led_state = False
lock = threading.Lock()

5. 创建LED闪烁线程函数

 def led_blink():
     while True:
         with lock:
             led.value = 0 if led_state else 1
         sleep(0.5)

6. 创建并启动LED闪烁线程:

 led_thread = threading.Thread(target=led_blink)
 led_thread.start()

7. 循环读取摄像头的帧:

 while True:
     ret, frame = cap.read()
     if not ret:
         print("无法读取摄像头的帧")
         break

8. 转换为灰度图像:

 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

9. 进行动作检测:

 if prev_frame is not None:
     frame_diff = cv2.absdiff(prev_frame, gray)
     _, thresh = cv2.threshold(frame_diff, 60, 255, cv2.THRESH_BINARY)
     motion_detected = cv2.countNonZero(thresh) > 0
 prev_frame = gray

10. 根据动作检测结果设置LED状态:

 with lock:
     if motion_detected:
         led_state = True
     else:
         led_state = False

11. 在窗口中显示帧

 cv2.imshow("Camera", frame)

12. 检测按键,如果按下 ‘q’ 键则退出循环:

 key = cv2.waitKey(1)
 if key == ord("q"):
     break

13. 释放摄像头资源:

 cap.release()

14. 关闭窗口:

 cv2.destroyAllWindows()

15. 等待LED闪烁线程结束:

 led_thread.join()

源码:
核桃派简易监控警示功能.zip (1.2 KB)

废话开始:要是代码不能用评论区找我就好,另外要是这篇帖子帮助到了你,拜托你用发财的手给我点点下方的小爱心。不要当白嫖怪!!!
你可以改成识别到人脸之后,来控制蜂鸣器也行,或者设置好播放你所要的媒体文件都可以,你们自己看着扩展用吧。

f52fc43c9ce9849691ead7b51b792654

3 个赞

如何安装opencv?

1 个赞

安装opencv:
sudo apt-get update
sudo apt-get install -y libopencv-dev python3-opencv

2 个赞