您的位置:首页 > 其它

树莓派+摄像头实现对移动物体的检测

2019-06-22 09:56 751 查看

在上一篇文章中实现了树莓派下对摄像头的调用,有兴趣的可以看一下:python+opencv实现摄像头调用的方法

接下来,我们将使用python+opencv实现对移动物体的检测

一、环境变量的配置

我们可以参照上一篇文章对我们的树莓派进行环境的配置

当我们将cv2的库安装之后,就可以实现对摄像头的操作

二、摄像头的连接

在此实验中,我使用的为usb摄像头

当我们连接摄像头之后,终端输入

ls /dev/video*

如果终端提示如下:

则表示摄像头连接成功

三、编码实现对移动物体的检测

使用python编写程序,实现对移动物体的检测,代码如下

#encoding=utf-8
import RPi.GPIO as GPIO
import cv2
import time
import os

GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.OUT)

camera = cv2.VideoCapture(0)
if camera is None:
print('please connect the camera')
exit()

fps = 30
pre_frame = None

led = False

while True:
start = time.time()
res, cur_frame = camera.read()
if res != True:
break
end = time.time()
seconds = end - start
if seconds < 1.0/fps:
time.sleep(1.0/fps - seconds)

cv2.namedWindow('img',0);
#cv2.imshow('img', cur_frame)
key = cv2.waitKey(30) & 0xff
if key == 27:
break

gray_img = cv2.cvtColor(cur_frame, cv2.COLOR_BGR2GRAY)
gray_img = cv2.resize(gray_img, (500, 500))
gray_img = cv2.GaussianBlur(gray_img, (21, 21), 0)

if pre_frame is None:
pre_frame = gray_img
else:
img_delta = cv2.absdiff(pre_frame, gray_img)
thresh = cv2.threshold(img_delta, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)

contours, hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
if cv2.contourArea(c) < 1000:
continue
else:
(x,y,w,h) = cv2.boundingRect(c)
cv2.rectangle(cur_frame,(x,y),(x+w,y+h),(0,255,0),2)

print("something is moving!!!")
led = True
if led == True:
for i in range(30):
GPIO.output(18,GPIO.HIGH)
time.sleep(0.03)
GPIO.output(18,GPIO.LOW)
time.sleep(0.03)
break

cv2.imshow('img', cur_frame)
pre_frame = gray_img

camera.release()
cv2.destroyAllWindows()

我的树莓派终端不能显示中文,因此会出现乱码

Ubuntu下的运行结果如下

树莓派下执行结果如下:

此外,在检测物体移动的同时,添加了led闪烁以及框选移动部分的功能,led安装方法请移步之前的博客

文章参考链接:OpenCV检测场景内是否有移动物体

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  树莓派 摄像头