python实现运动探测
时间: 2023-07-11 09:35:31 浏览: 96
要实现运动探测,可以借助电脑摄像头、OpenCV 库和Python语言编写程序。具体步骤如下:
1. 导入OpenCV库和numpy库
```
import cv2
import numpy as np
```
2. 打开电脑摄像头
```
cap = cv2.VideoCapture(0)
```
3. 定义背景图片
```
background = None
```
4. 不断读取摄像头的每一帧图像,进行处理
```
while True:
ret, frame = cap.read()
if not ret:
break
```
5. 将读取到的图像转换为灰度图
```
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
```
6. 对第一帧图像进行处理,得到背景图片
```
if background is None:
background = gray
continue
```
7. 计算当前帧图像与背景图片的差异
```
diff = cv2.absdiff(background, gray)
```
8. 对差异图像进行阈值处理,可以设置一个阈值来筛选出运动物体
```
thresh = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)[1]
```
9. 对阈值图像进行膨胀处理,可以去掉一些小的噪点
```
thresh = cv2.dilate(thresh, None, iterations=2)
```
10. 在差异图像中找到轮廓,利用轮廓信息来确定运动物体的位置
```
contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) < 1000:
continue
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
```
11. 显示处理后的图像
```
cv2.imshow("frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
```
完整代码如下:
```
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
background = None
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
if background is None:
background = gray
continue
diff = cv2.absdiff(background, gray)
thresh = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) < 1000:
continue
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
```
这样就可以实现简单的运动探测了。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)