智能摄像头DIY教程
off999 2024-12-13 15:37 31 浏览 0 评论
你要去度假,想看看家里的情况吗?你想了解人工智能和计算机视觉吗?你有 Raspberry Pi、网络摄像头和一些空闲时间吗?那么这个项目就是为你准备的!
在本文中,我们将介绍如何使用 Raspberry Pi 在 Python 中创建智能监控摄像头,成本低廉,而且不会失去对数据的控制。
这款摄像头将能够检测到网络摄像头视野范围内的任何人,并向您发送带有照片的电子邮件警报。
为了开展这个项目,我们将使用计算机视觉,这是人工智能的一个分支,它可以通过分析组成图像的像素来处理图像上的信息。
让我们从基础知识开始,了解人工智能 (AI) 是什么以及保护个人数据 (RGPD) 的重要性。
NSDT工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器 - REVIT导出3D模型插件 - 3D模型语义搜索引擎 - AI模型在线查看 - Three.js虚拟轴心开发包 - 3D模型在线减面 - STL模型在线切割
1、你提到人工智能,它是什么?
人工智能 (AI) 是一种模仿人类智能的计算机程序,可以执行通常需要人类智能的任务,例如语音识别、机器翻译、国际象棋或自动驾驶。
计算机视觉是人工智能的一个分支学科,专注于图像和视频的处理和分析。它的目的是让机器能够看到和理解视觉世界,就像人类用眼睛和大脑一样。
计算机视觉基于数学和统计技术,如今有许多实际应用,包括安全、医学、机器人技术、汽车工业、娱乐和商业。例如,计算机视觉可用于预测和帮助检测 X 射线或 MRI 上的病理,在复杂环境中引导机器人,识别道路上的路标或行人,为虚拟角色制作动画或识别货架上的产品。
2、GDPR:通用数据保护条例
那么如何保护你的面部和身份等个人数据呢?
为什么我们应该尊重 GDPR 和数据保护?
与任何技术一样,计算机视觉既有优势,也有风险。主要风险之一是尊重被摄像机拍摄或拍照的人的隐私和个人数据。图像和视频可能包含敏感信息,例如身份、面部表情、情绪、位置、活动等。……
《通用数据保护条例》(GDPR)是一部欧洲法律,旨在保护欧洲公民在处理个人数据方面的权利和自由。
《通用数据保护条例》要求数据控制者遵守合法性、公平性和透明度、目的限制、数据最小化、准确性和保留的原则。《通用数据保护条例》还赋予受数据处理影响的人权利,例如访问权、更正权、删除权、可移植性或反对权。
因此,在使用计算机视觉时,尤其是对于监控摄像机项目,尊重 GDPR 和数据所有权至关重要,这就是为什么开发自己的解决方案意味着您可以保留对整个数据生命周期的控制权:获取、处理、使用和存储。
3、所需的物料
- Raspberry Pi:运行计算机视觉并执行所有任务
- 网络摄像头:用于获取图像
- [可选] Arduino KY-035 和 ADS1115:可用于检测门打开的磁传感器。它必须与 16 位模拟数字转换器 (ADC) 结合使用,才能将信息传输到 Raspberry Pi。
Raspberry Pi 将成为该机制的大脑。它将接收网络摄像头捕获的您家的图像,使用计算机视觉模型对其进行处理,然后发送电子邮件。
Raspberry Pi 使用 Python 编程语言,要使用 Tensorflow Lite 模型,您需要安装两个库:
opencv-python 是一个开源库,包含数百种计算机视觉算法。它允许您使用网络摄像头、处理图像并将其传输到模型。
为了使用这些库,需要运行以下命令来安装 Python 库:
pip install numpy imutils opencv-python
pip install ultralytics4、Yolo
本教程的目的不是训练你自己的模型,而是测试一种使用已经训练有素且经过验证的模型(如 Yolo)即可轻松实现的方法。
Yolo 是一种用于检测图像中对象的算法。它是一种用于检测和分类图像中对象(如人、汽车或物体)的人工智能方法。为了实现这一点,它使用卷积神经网络,这是一种能够分析图像中的像素并从中提取有用信息的模型。
Yolo 不是多次查看图像来查找对象,而是将其分成小单元。每个单元都试图预测其周边的物体在哪里,以及它们属于哪个类别。它通过计算边界框(即围绕对象的矩形)的坐标和尺寸以及属于每个类别的概率来实现这一点。例如,一个单元可以说一个物体是人的概率为 80%,是自行车的概率为 20%。
示例:让我们想象一张有汽车和行人的街道图片。YOLO 会将此图像划分为网格,预测每辆汽车和行人周围的边界框,为每个框分配一个类别(汽车、行人),并消除冗余或不太可能的预测。最终结果是,图像中每个检测到的物体周围都有精确的边界框,这一切都是一次性完成的,因此得名“你只需看一次”。
在了解了 Yolo 算法的工作原理后,我们现在将研究如何使用 Python 和 Raspberry Pi 来创建智能监控摄像头。
此用例的目的是检测是否有人进入摄像头拍摄的区域,并发送带有照片的警报电子邮件。因此,我们将这种方法分为三个主要阶段:
- 加载 Yolo 模型,这将使我们能够检测摄像头捕获的图像中的物体。
- 从模型中进行推断,它将返回检测到的物体的边界框和类别,并检查其中是否有任何物体与人相对应。
- 发送电子邮件,它将使用 smtplib 库将带有照片的消息发送到预定义的地址。
我们将在本文的其余部分更详细地介绍每个步骤。
5、代码实现
代码的第一部分将用于加载预先训练的 Yolo 模型。为此,我们首先选择Ultralytics仓库:
然后将其本地下载到 RaspberryPi 上。Yolo 模型已初始化(程序启动时下载 .pt 文件)。
from ultralytics import YOLO
#load and save YOLO model
path_dir = "/home/florianberga/Desktop/camera/"
model = YOLO(path_dir+"yolov8n.pt"). #yolov5nu.pt is better for my case
#show all classes of the Yolo model
print(model.names)现在,模型已经可用,是时候对其进行测试了。
5.1 Yolo 模型推理
计算机视觉模型推理涉及使用经过训练的模型分析图像或视频并检测物体、面部、动作或任何其他相关元素。推理将视觉数据转化为可操作的信息,然后可用于做出决策、自动化流程或改进服务。
# initialize the video capture object
vs = VideoStream(src=0, resolution=(700, 700)).start()
#define the accuracy min to validate the class identified
accuracy_min = 0.7
#define the colour of the text and the bounding box on the picture
Green_RGB_color = (0, 255, 0)
i=0
while True:
try : # if the camera stop to work
#get the picture of the webcam
frame = vs.read()
#press key Q to exit
if cv2.waitKey(1) & 0xFF ==ord('q'):
break
i=i+1
if i>=15 :# 1 image per second is enough
# we run the model of YOLO on the picture
detection = model(frame)[0]
Label_total=""
nb_person=0
# loop on all the detections
for box in detection.boxes:
#we extract the accuracy with the detection
data=box.data.tolist()[0]
accuracy = data[4]
#we extract the class label name
label=model.names.get(box.cls.item())
# filter out bad detections
if float(accuracy) < accuracy_min :
continue
else:
Label_total=Label_total+label+'_'
if label=="person":
#A person has been detected per Yolo
nb_person=nb_person+1
# draw the bounding box on the picture
xmin, ymin, xmax, ymax = int(data[0]), int(data[1]), int(data[2]), int(data[3])
cv2.rectangle(frame, (xmin, ymin) , (xmax, ymax), Green_RGB_color, 2)
#draw confidence and label
y = ymin - 15 if ymin - 15 > 15 else ymin + 15
cv2.putText(frame, "{} {:.1f}%".format(label,float(confidence*100)), (xmin, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, Green_RGB_color, 2)
if nb_person>0:
today = datetime.date.today()
datetoday = today.strftime("%Y-%m-%d")
now = datetime.datetime.now()
current_time = now.strftime("%H:%M:%S")
cv2.putText(frame, datetoday+" "+current_time, (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 1)
#we would like to save the picture : Create Dir if they don't exist
if os.path.exists(path_dir+'folder_imwrite/')==False:
os.mkdir(path_dir+'folder_imwrite/')
if os.path.exists(path_dir+'folder_imwrite/'+str(datetoday))==False:
os.mkdir(path_dir+'folder_imwrite/'+str(datetoday))
#save
cv2.imwrite(path_dir+'folder_imwrite/'+str(datetoday)+'/'+current_time+'__'+str(nb_person)+"-pers__"+str(j)+'.jpg', frame)
# we would like to show the frame to our screen
#cv2.imshow("Frame", frame)
except :
print("Error camera")
#vs.release()
vs.stop()
cv2.destroyAllWindows()一旦模型识别出图像中的某个人,它就会进入下一阶段:发送电子邮件让人们知道有人在那里。
5.2 发送邮件
在了解如何使用 Python 发送邮件之前,这里有一些提示和先决条件:
就我而言,我创建了一个独特的 Gmail 帐户:camera.xxxx@gmail.com。应用密码是一个 16 位密码,它允许不太安全的应用或设备访问你的 Google 帐户。应用密码只能用于已启用两步验证的帐户。要了解如何恢复密码请访问这里。
def envoie_mail(nb_people_max, table_photo):
email_subject = "Home XXX - Detection someone at home"
sender_email_address = "Camera.xxxx@gmail.com"
receiver_email_address = "xxx.xxxx@gmail.com"
email_smtp = "smtp.gmail.com"
email_password = "xxxx xxxx xxxx xxxx" #App Password : https://support.google.com/mail/answer/185833?hl=en
# create an email message object
message = EmailMessage()
# configure email headers
message['Subject'] = email_subject
message['From'] = sender_email_address
message['To'] = receiver_email_address
# set email body text
message.set_content(str(nb_people_max)+" people detected at home")
i_image=0
while i_image<len(table_photo):
image_data=""
# open image as a binary file and read the contents
with open(table_photo[i_image], 'rb') as file:
image_data = file.read()
# attach image to email
# message.add_attachment(image_data, maintype='image', subtype=imghdr.what(None, image_data))
message.add_attachment(image_data, maintype='image', subtype="jpeg")
i_image=i_image+1
# set smtp server and port
server = smtplib.SMTP(email_smtp, '587')
# identify this client to the SMTP server
server.ehlo()
# secure the SMTP connection
server.starttls()
# login to email account
server.login(sender_email_address, email_password)
# send email
server.send_message(message)
# close connection to server
server.quit()main.py 的完整代码:
# -*- coding: utf-8 -*-
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import threading
import datetime
from ultralytics import YOLO
import cv2
from imutils.video import VideoStream
import screeninfo
import os
import smtplib
from email.message import EmailMessage
#load and save YOLO model
path_dir = "/home/florianberga/Desktop/camera/"
model = YOLO(path_dir+"yolov8n.pt") #yolov5nu.pt is better for my case
accuracy_min = 0.7
Green_RGB_color = (0, 255, 0)
def envoie_mail(nb_people_max, table_photo):
email_subject = "Home XXX - Detecting someone at home"
sender_email_address = "Camera.xxxx@gmail.com"
receiver_email_address = "xxx.xxxx@gmail.com"
email_smtp = "smtp.gmail.com"
email_password = "xxxx xxxx xxxx xxxx" #App Passworld
# create an email message object
message = EmailMessage()
# configure email headers
message['Subject'] = email_subject
message['From'] = sender_email_address
message['To'] = receiver_email_address
# set email body text
message.set_content(str(nb_people_max)+" people detected at home")
i_image=0
while i_image<len(table_photo):
image_data=""
# open image as a binary file and read the contents
with open(table_photo[i_image], 'rb') as file:
image_data = file.read()
# attach image to email
# message.add_attachment(image_data, maintype='image', subtype=imghdr.what(None, image_data))
message.add_attachment(image_data, maintype='image', subtype="jpeg")
i_image=i_image+1
# set smtp server and port
server = smtplib.SMTP(email_smtp, '587')
# identify this client to the SMTP server
server.ehlo()
# secure the SMTP connection
server.starttls()
# login to email account
server.login(sender_email_address, email_password)
# send email
server.send_message(message)
# close connection to server
server.quit()
# initialize the video capture object
vs = VideoStream(src=0, resolution=(700, 700)).start()
i=0
j=0
nb_image_mail=0
nb_personne_max=0
table_path_image=[]
while True:
try : # if the camera stop to work
#get the picture of the webcam
frame = vs.read()
#press key Q to exit
if cv2.waitKey(1) & 0xFF ==ord('q'):
break
i=i+1
if i>=15 :# 1 image per second is enough
# we run the model of YOLO on the picture
detection = model(frame)[0]
Label_total=""
nb_person=0
# loop on all the detections
for box in detection.boxes:
#we extract the accuracy with the detection
data=box.data.tolist()[0]
accuracy = data[4]
#we extract the class label name
label=model.names.get(box.cls.item())
# filter out bad detections
if float(accuracy) < accuracy_min :
continue
else:
Label_total=Label_total+label+'_'
if label=="person":
#A person has been detected per Yolo
nb_person=nb_person+1
# draw the bounding box on the picture
xmin, ymin, xmax, ymax = int(data[0]), int(data[1]), int(data[2]), int(data[3])
cv2.rectangle(frame, (xmin, ymin) , (xmax, ymax), Green_RGB_color, 2)
#draw confidence and label
y = ymin - 15 if ymin - 15 > 15 else ymin + 15
cv2.putText(frame, "{} {:.1f}%".format(label,float(confidence*100)), (xmin, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, Green_RGB_color, 2)
if nb_person>0:
today = datetime.date.today()
datetoday = today.strftime("%Y-%m-%d")
now = datetime.datetime.now()
current_time = now.strftime("%H:%M:%S")
cv2.putText(frame, datetoday+" "+current_time, (50,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 1)
#we would like to save the picture : Create Dir if they don't exist
if os.path.exists(path_dir+'folder_imwrite/')==False:
os.mkdir(path_dir+'folder_imwrite/')
if os.path.exists(path_dir+'folder_imwrite/'+str(datetoday))==False:
os.mkdir(path_dir+'folder_imwrite/'+str(datetoday))
#save
cv2.imwrite(path_dir+'folder_imwrite/'+str(datetoday)+'/'+current_time+'__'+str(nb_person)+"-pers__"+str(j)+'.jpg', frame)
# we would like to show the frame to our screen
#cv2.imshow("Frame", frame)
bilan_day_nbpersonnes.append(str(nb_person))
bilan_heure_presence.append(str(current_time))
bilan_day_presence.append(str(datetoday))
if nb_personne_max<nb_person:
nb_personne_max=nb_person
if j>1800: #noboady during 1h (1800)
table_path_image.append(path_dir+'folder_imwrite/'+str(datetoday)+'/'+current_time+'__'+str(nb_person)+"-pers__"+str(j)+'.jpg')
#We can send the email to inform there is someone
# We would like to collect other pictures before to send the mail : to catch other pictures : 3
if nb_image_mail>=3:
#we send the mail
envoie_mail(nb_personne_max, table_path_image)
j=0
nb_image_mail=0
nb_personne_max=0
table_path_image.clear()
else:
nb_image_mail=nb_image_mail+1
else:
today = datetime.date.today()
datetoday = today.strftime("%Y-%m-%d")
now = datetime.datetime.now()
current_time = now.strftime("%H:%M:%S")
j=j+1
i=0
except :
print("Error camera")
#video_cap.release()
vs.stop()
cv2.destroyAllWindows()5.3 在 Raspberry Pi 开启时启动该机制
如果你想在开启 Raspberry Pi 时运行代码,只需修改设置“ crontab -e ”:
你可以使用像 nano 这样的控制台模式编辑器。只需添加以下带有 @reboot 选项的行:
@reboot python3 /home/florianberga/Desktop/camera/main.py &需要注意以下两点:
- 使用绝对路径
- 在行尾添加 & 以在单独的进程中启动命令。如果你的软件没有快速放弃,这可以避免阻止 Raspberry Pi 的启动。
6、结束语
我希望这对你在自己的项目中使用计算机视觉有所帮助和启发。当然,这只是一个演示,可以通过面部识别和其他训练模型以及其他功能轻松改进……
原文链接:智能摄像头DIY教程 - BimAnt
相关推荐
- win7连不上win10打印机拒绝访问
-
原因及解决方法:1.在Win10Cortana搜索框中,搜索控制面板将打开;2.转到控制面板,选择查看方法作为一个小图标,然后单击程序和功能;3.单击以启用或禁用Windows功能选项;4....
- 电脑主机不启动但通电(电脑主机开机不通电没反应)
-
第1步:首先检查电脑的外部接线是否接好,把各个连线重新插一遍,看故障是否排除。第2步:如果故障依旧,接着打开主机箱查看机箱内有无多余金属物,或主板变形造成的短路,闻一下机箱内有无烧焦的糊味,主板上有无...
- 苹果一体机怎么重装系统(苹果一体机重装系统win10)
-
苹果更换硬盘后,如果您没有创建一个启动磁盘或者使用TimeMachine备份系统,您可以按照以下步骤重新安装操作系统:1.准备一个可用于安装系统的启动磁盘。您可以使用官方提供的macOS安装介质(...
-
- 装系统的u盘怎么制作(装系统怎么制作u盘启动盘)
-
1、下载安装u当家u盘启动盘制作工具,完成之后打开该软件2、将之前准备好的U盘插入电脑,U当家会自动识别并选为默认,如果有多个U盘可以在“选择U盘”的下拉框中选择要制作成U盘启动盘的U盘。3、点击下面的“一键制作”按钮。(如果是电脑主板是U...
-
2025-11-15 07:03 off999
- 台电u盘怎么样
-
感觉台电U盘还是可以的,我知道台电是国内最成功的数码产品制造商之一,是一个致力于IT及消费数码类产品研发、生产、销售及服务的一体化品牌,U盘很好用,用的人很多。威刚是480Mbit/S只是USB2...
- u盘重装系统蓝屏进不去(u盘装系统重启蓝屏)
-
尊敬的用户您好:可按下面的步骤进行系统盘装系统:1.买一张win7光盘,将系统光盘放入光驱里。2.打开电源,然后观察屏幕的提示,在启动系统之前有按“f2进行bios设置。3.设置启动方式。找到boot...
- win快捷键大全(win快捷键大全表)
-
win快捷键:单独按Windows:显示或隐藏“开始”功能表Windows+BREAK:显示“系统属性”对话框Windows+D:显示桌面或恢复桌面Windows+M:最小化所有窗口Windows...
- u盘突然要格式化怎么回事(用着的u盘突然要格式化)
-
U盘提示格式化的原因可能有以下几点:文件系统损坏:U盘的文件系统可能出现损坏,导致无法正常读取和写入数据。病毒感染:U盘可能被病毒感染,病毒会破坏文件系统或隐藏文件。不兼容的文件系统:U盘可能使用了一...
- 路由器pppoe怎么设置(路由器如何设置pppoe上网)
-
移动宽带PPPOE是不用设置的,你只要把帐号和密码填上其他都不选就能上网。但是要注意连接到你电脑的网线是直接经过一个路由器后连接到猫上的,因为我见过有人是这样连接的猫---路由器---路由器---电脑...
- win7桌面图标设置在哪里(win7桌面图标在哪个文件夹)
-
要调出Win7桌面图标,首先需要进入桌面。可以通过点击任务栏上方的“显示桌面”按钮或按下Windows键+D快捷键进入桌面。在桌面上右键单击空白区域,选择“个性化”,然后选择“更改桌面图标”选项。在弹...
- win7手机壁纸(windows7手机桌面主题)
-
1.首先我们打开手机进入到桌面,找到设置图标点击打开。华为手机如何设置自定义锁屏壁纸2.进入到设置界面之后,点击下方的显示选项。华为手机如何设置自定义锁屏壁纸3.然后我们就可以在显示界面中找到壁纸...
- 怎么开启路由器wifi(怎么开启路由器的dhcp功能)
-
把路由器改为开放网络方法如下:1、打开浏览器,在地址栏输入路由器网关IP地址(路由器背后的标签上有,一般是192.168.1.1),输入登录用户名和密码(一般均为admin);2、登录成功后就显示运行...
- win10加载不出来桌面黑屏(window10加载不出来)
-
方法一、如果是遇到了突发性黑屏首先尝试使用Ctrl+Alt+Delete组合键来进行电脑重启一般重启可以解决大部分黑屏故障。win10电脑黑屏按什么键恢复_win10电脑黑屏一键恢复的方法方法...
- 怎么用火绒关闭win安全中心(win10火绒安全软件怎么关闭)
-
一、火绒防火墙关闭方法在电脑上运行火绒软件后,点击首页界面的“防护中心”,在病毒防护界面可以关闭文件、U盘、邮件等保护功能,。系统防护:在该界面可以关闭系统防护功能,。网络防护:可以关闭网络保护等功...
- 微软应用商店下载手机版(微软应用商店在哪下)
-
、在桌面任务栏找到微软应用商店,点击并打开。2、进入页面后点击【应用】,进入应用页面。3、在页面里往下移动,找到热门应用,找到一个软件,点击进入。4、进入页面后,点击【安装】,软件会自动安装,安装完毕...
欢迎 你 发表评论:
- 一周热门
-
-
抖音上好看的小姐姐,Python给你都下载了
-
全网最简单易懂!495页Python漫画教程,高清PDF版免费下载
-
Python 3.14 的 UUIDv6/v7/v8 上新,别再用 uuid4 () 啦!
-
python入门到脱坑 输入与输出—str()函数
-
飞牛NAS部署TVGate Docker项目,实现内网一键转发、代理、jx
-
宝塔面板如何添加免费waf防火墙?(宝塔面板开启https)
-
Python三目运算基础与进阶_python三目运算符判断三个变量
-
(新版)Python 分布式爬虫与 JS 逆向进阶实战吾爱分享
-
慕ke 前端工程师2024「完整」
-
失业程序员复习python笔记——条件与循环
-
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
