opencv+python检测入侵物体
2017-07-08 23:19
363 查看
opencv+python检测入侵物体
去年暑假在家的时候,参考别人的博客,编写了这个程序,本想着继续完善一下 ,却一直没时间做。偶然翻到了这个程序,决定放上来。因为时间太久,我也没办法把当初参考的博客放上来(其实是因为懒得找),如果大家需要,我会放上链接。
环境:opencv2.4+python2.7
编辑器:spyder
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import cv2 import time import datetime cap = cv2.VideoCapture(0) avg = None lastUploaded = datetime.datetime.now() motionCounter = 0 time.sleep(10) while(True): # 逐帧获取图像 tiestamp = datetime.datetime.now() ret, frame = cap.read() text = "unoccupied" if not ret: break # 对每帧图像进行操作 gray = cv2.resize(frame,width=500)#调整大小 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)#变成灰色图像 gray = cv2.GaussianBlur(gray,(21,21),0)#高斯滤波 if avg is None: avg = gray.copy().astype("float") continue cv2.accumulateWeighted(gray,avg,0.5) # 显示处理后的图像 cv2.imshow('frame',gray) #计算当前帧与第一帧的区别 frameDelta = cv2.absdiff(gray,cv2.convertScaleAbs(avg)) # cv2.imshow('first2',frameDelta) #填充孔洞 thresh = cv2.threshold(frameDelta, 45, 255, cv2.THRESH_BINARY)[1] thresh = cv2.dilate(thresh, None, iterations=2) cv2.imshow('thresh',thresh) #查找轮廓 contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2:] # cv2.imshow('thresh2',thresh.copy()) for c in contours: # if the contour is too small, ignore it if cv2.contourArea(c) < 500: continue # 计算轮廓的边界框,在当前帧中画出该框 (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow('found',frame) text = "Occupied" cv2.putText(frame, "Room Status: {}".format(text), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) cv2.putText(frame, datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p"), (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1) #if text == "Occupied": # if (timestamp-lastUploaded).second>=2: # motionCounter+=1 #if motionCounter>=23: if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
里面调用的是笔记本自带的摄像头来获取图像,如果想要采用别的方式,需要更改一下。如果效果要想好一点儿,可能还需要调整一下参数。程序已经测过,没有问题。
相关文章推荐
- python opencv 检测移动物体并截图保存
- 使用Python和OpenCV检测图像中的物体并将物体裁剪下来
- python-opencv2利用cv2.findContours()函数来查找检测物体的轮廓
- 使用Python和OpenCV检测图像中的物体并将物体裁剪下来
- 【Python+OpenCV】实现检测场景内是否有物体移动,并进行人脸检测抓拍
- python3.6.3+opencv3.3.0学习笔记九--动态物体检测
- 使用Python和OpenCV检测图像中的物体并将物体裁剪下来
- Python__OpenCV检测图像物体轮廓
- opencv 运动物体检测函数介绍
- Python和OpenCV简单的人脸检测程序
- 【转】OpenCV--锁定老帖子 主题:人脸检测原理及示例(OpenCV+Python)
- Python OpenCV -- 轮廓检测 (十四)
- OpenCV检测运动物体的基础_特征提取
- Opencv2.2 Python 人脸检测
- opencv for python 之 突出点检测
- python+OpenCV进行人脸检测
- python+OpenCV进行人脸检测【转】
- OpenCV 使用光流法检测物体运动
- opencv 检测运动物体 例子时出现图像反转
- Python OpenCV -- Canny 边缘检测 (十一)