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

在上一篇文章中实现了树莓派下对摄像头的调用,有兴趣的可以看一下https://blog.csdn.net/Wangguang_/article/details/89850615

接下来,我们将使用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下的运行结果如下

树莓派+摄像头实现对移动物体的检测_第1张图片

树莓派下执行结果如下:

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

https://blog.csdn.net/Wangguang_/article/details/90258604

文章参考链接:http://blog.topspeedsnail.com/archives/10797

你可能感兴趣的:(树莓派,Python)