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

yipeiwu_com6年前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 通过手机号识别出对应的微信性别,具体代码如下所述: def getGender(self,tel): self.d(resourceId="com.tencent....

Django 路由控制的实现代码

一、URL路由基础 URL是web服务的路口,用户通过浏览器发送过来的任何请求都会被发送到一个指定的URL地址里,然后被响应。 在django项目中编写路由就是向外暴露我们接收哪些U...

打印出python 当前全局变量和入口参数的所有属性

def cndebug(obj=False): """ Author : Nemon Update : 2009.7.1 TO use : cndebug(obj) or cndebug...

TensorFLow 不同大小图片的TFrecords存取实例

全部存入一个TFrecords文件,然后读取并显示第一张。 不多写了,直接贴代码。 from PIL import Image import numpy as np import m...

以windows service方式运行Python程序的方法

本文实例讲述了以windows service方式运行Python程序的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python # coding...