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

yipeiwu_com7年前Python基础

在上一篇文章中实现了树莓派下对摄像头的调用,有兴趣的可以看一下: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检测场景内是否有移动物体

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

分析在Python中何种情况下需要使用断言

这个问题是如何在一些场景下使用断言表达式,通常会有人误用它,所以我决定写一篇文章来说明何时使用断言,什么时候不用。 为那些还不清楚它的人,Python的assert是用来检查一个条件,如...

python实现每次处理一个字符的三种方法

本文实例讲述了python每次处理一个字符的三种方法。分享给大家供大家参考。 具体方法如下: a_string = "abccdea" print 'the first' f...

numpy.array 操作使用简单总结

import numpy as np numpy.array 常用变量及参数 dtype变量,用来存放数据类型, 创建数组时可以同时指定。 shape变量, 存放数组的大...

让 python 命令行也可以自动补全

许多人都知道 iPython 有很好的自动补全能力,但是就未必知道 python 也同样可以 Tab 键补全, 您可以在启动 python 后,执行下 复制代码 代码如下: import...

pytorch索引查找 index_select的例子

index_select anchor_w = self.FloatTensor(self.scaled_anchors).index_select(1, self.LongTensor...