winform 画面关闭返回值_opencv+python判断画面动静

  • 原理:每隔一个时间间隔采集一幅图片,通过比较前后两幅图片像素变化来判断画面中是否有物体在运动
  • 实现方法:首先将两幅图都转为灰度图,对两幅图进行相减,再算所得差的平均值,然后设置一个阈值,如果这一平均值大于阈值,认为画面中有物体在运动;反之则认为画面中没有物体在运动。阈值的目的是为了避免画面中的微小变化使识别效果降低。
  • 代码如下:
 import cv2
 import time
 import numpy as np
 ​
 video_file = "./videos/video.mp4"        
 cap = cv2.VideoCapture(video_file)  #读取视频文件,参数设置为0表示从摄像头获取图像
 ​
 _, frame1 = cap.read()
 img1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)   #将图片转为灰度图,第一个返回值表示是否转换成功,第二个返回值就是灰度图了
 start = time.time()
 ​
 def moving_detect(frame1, frame2):
     img1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
     img2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
     grey_diff = cv2.absdiff(img1, img2)              #计算两幅图的像素差
     change = np.average(grey_diff)
     
     if change > 10:    #当两幅图的差异大于给定的值后,认为画面有物体在动
         cv2.putText(frame2, 'moving', (100, 30), 2, 1,(0,255,0),2,cv2.LINE_AA)
     else:
         cv2.putText(frame2, 'quiet', (100, 30), 2, 1, (255, 0, 0), 2, cv2.LINE_AA)
     cv2.imshow("output", frame2)
 ​
 while True:
     end = time.time()
     if (end - start > 2):                  #每隔2秒拍一幅图,比较前后两幅图的差异
         start = time.time()
         _, frame1 = cap.read()
 ​
     _, frame2 = cap.read()
     moving_detect(frame1, frame2)
     if cv2.waitKey(5) & 0xFF == ord('q'):        #按下q停止运行程序
         break
 ​
 # 最后,关闭所有窗口
 cap.release()
 cv2.destroyAllWindows()
 ​

winform 画面关闭返回值_opencv+python判断画面动静_第1张图片

winform 画面关闭返回值_opencv+python判断画面动静_第2张图片

(这支笔是在运动的)

你可能感兴趣的:(winform,画面关闭返回值)