• 正文
  • 相关推荐
申请入驻 产业图谱

自动化树莓派教程:带快照功能的摄像头动作检测器!

08/25 15:55
1094
加入交流群
扫码加入
获取工程师必备礼包
参与热点资讯讨论

让我们开始今天的内容!

如果你和我一样,你的树莓派总是运行着某些东西:可能是备份、网络监控,或者只是一个简单的脚本。但是每天重复同样的任务很快就会让人厌烦。这时Python就派上用场了。只需几个简单的脚本,你的树莓派就能自动处理这些无聊的事情。我测试了许多脚本,并挑选出了其中最有用的几个。

Python脚本可以在树莓派上用于自动化功能任务,如备份、监控、警报和设备控制,只需几行代码即可实现。与bash脚本相比,它们更容易编写、阅读和扩展,尤其是在使用库或Web API时。

在本文中,我将分享一些我最常用的Python脚本,这些脚本让我的树莓派变得更智能、更省心。你会发现一些想法、代码片段和提示,你可以立即应用它们,不需要高级技能。

带快照功能的摄像头动作检测器

将树莓派变成一个基础的安全系统听起来很复杂,但实际上比您想象的要简单得多。通过使用树莓派的摄像头模块和一些计算机视觉技术,您可以轻松实现这一目标。

OpenCV 是一个开源库,兼容 Python 和 C++ 等语言。它允许您构建计算机视觉和机器学习项目。使用 OpenCV,您可以实现人脸识别、手势识别等功能。

https://raspberrytips.com/install-opencv-on-raspberry-pi/

您可以按照以下指南配置树莓派摄像头以与 Python 一起使用:2025 年如何使用 Python 与树莓派摄像头。

https://raspberrytips.com/picamera2-raspberry-pi/

您可以使用以下命令在树莓派上安装 OpenCV:

sudo apt install python3-opencv

然后,您可以在 Python 脚本中使用 OpenCV 创建一个运动检测算法,如下所示:

import cv2# Capture video streamcam = cv2.VideoCapture(0)# Read the first frame and preprocess it_, frame1 = cam.read()gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)gray1 = cv2.GaussianBlur(gray1, (21, 21), 0)while True:    # Read the next frame    _, frame2 = cam.read()    gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)    gray2 = cv2.GaussianBlur(gray2, (21, 21), 0)    # Compute difference between frames    delta = cv2.absdiff(gray1, gray2)    thresh = cv2.threshold(delta, 25, 255, cv2.THRESH_BINARY)[1]    thresh = cv2.dilate(thresh, None, iterations=2)    # Find contours (moving areas)    contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)    # Check for motion    motion_detected = any(cv2.contourArea(c) > 1000 for c in contours)    if motion_detected:        print(" Motion detected!")    # Update the baseline frame    gray1 = gray2.copy()    # Exit on 'q'    if cv2.waitKey(10) == ord('q'):        breakcam.release()cv2.destroyAllWindows()

这个运动检测脚本可以通过简单的 Python 代码将检测到的图像通过电子邮件发送给您:

import smtplibfrom email.message import EmailMessagedef send_email(image_path):    # Set up the email details    msg = EmailMessage()    msg['Subject'] = ' Motion Detected on Raspberry Pi'    msg['From'] = 'your_email@gmail.com'    msg['To'] = 'recipient_email@gmail.com'    msg.set_content('Motion detected! See attached snapshot.')    # Attach the image    with open(image_path, 'rb') as f:        msg.add_attachment(f.read(), maintype='image', subtype='jpeg', filename='snapshot.jpg')    # Send via Gmail (or your preferred SMTP)    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:        smtp.login('your_email@gmail.com', 'your_app_password')        smtp.send_message(msg)        print(" Email sent successfully!")

通过结合这两个脚本,您可以让树莓派充当家庭哨兵。每当摄像头检测到任何运动时,它都会拍照并通过电子邮件发送给您。

您可以通过添加 HC-SR501 运动检测传感器来改进此项目,以增强系统的运动检测能力。

很多人一直以为树莓派(Raspberry Pi)只是创客圈子里的小玩具——一块信用卡大小的开发板,用来点亮 LED、跑个 Python 脚本、或者给中学生上一堂入门编程课。然而,事实远比想象震撼:树莓派已经悄悄完成了从“教学演示”到“工业级主力”的华丽转身,正在产线、机房、实验室甚至外太空里 7×24 小时不间断服役。

如果觉得文章不错记得点赞,推荐,分享~ 我们很乐意为您提供工业树莓派的解决方案,项目有需求请联系我们~ www.edatec.cn/cn

相关推荐