树莓派+摄像头实现对移动物体的检测
在上一篇文章中实现了树莓派下对摄像头的调用,有兴趣的可以看一下: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检测场景内是否有移动物体
相关推荐
LeeHDsniper 2020-11-05
橄榄 2020-11-03
wanshiyingg 2020-09-29
andonliu 2020-09-03
嵌入式开发爱好者 2020-08-28
lu00kill 2020-08-17
tianyayi 2020-08-16
LIEVEZ 2020-08-09
ohhardtoname 2020-07-25
LeeHDsniper 2020-07-19
shenxiuwen 2020-07-16
wzxxtt0 2020-06-25
mattraynor 2020-06-25
咏月东南 2020-06-10
wangz 2020-06-03
wanxuncpx 2020-06-01
tianyayi 2020-05-18
wanxuncpx 2020-05-15
mattraynor 2020-05-12
wzxxtt0 2020-05-12
LIEVEZ 2020-05-04
mattraynor 2020-05-01
LIEVEZ 2020-05-01
LIEVEZ 2020-05-01
LowisLucifer 2020-04-23
OathKeeper 2020-04-22
zcabcd 2020-04-18
wanxuncpx 2020-04-16
returnspace 2020-04-16
mattraynor 2020-04-14
tianyayi 2020-03-28
clamzxf 2020-03-28
Summer的小屋 2020-03-26
lu00kill 2020-03-17
yuancr 2020-03-04
wzxxtt0 2020-02-21
xinhao 2020-02-20
LIEVEZ 2020-02-17
wzxxtt0 2020-02-15
zhufu 2020-02-10