使用opencv3+python实现视频运动目标检测
本文主要实现了伯乐在线上的一个实践小项目,原文链接,用以巩固opencv视频操作知识内容。整个项目均有代码注释,通俗易懂,短短几十行就可以达到还算不错的实现效果,做起来成就感满满哒。打开编辑器,一起来感受下opencv+python在CV中的无穷魅力吧 ^_^
1 import argparse 2 import time 3 import imutils 4 import cv2 5 6 # 创建参数解析器并解析参数 7 ap = argparse.ArgumentParser() 8 ap.add_argument("-v", "--video", help="path of the video") 9 # 待检测目标的最小面积,该值需根据实际应用情况进行调整(原文为500) 10 ap.add_argument("-a", "--min-area", type=int, default=2000, help="minimum area size") 11 args = vars(ap.parse_args()) #@ 12 13 # 如果video参数为空,则从自带摄像头获取数据 14 if args.get("video") == None: 15 camera = cv2.VideoCapture(0) 16 # 否则读取指定的视频 17 else: 18 camera = cv2.VideoCapture(args["video"]) 19 20 21 # 开始之前先暂停一下,以便跑路(离开本本摄像头拍摄区域^_^) 22 print("Ready?") 23 time.sleep(1) 24 print("Action!") 25 26 # 初始化视频第一帧 27 firstRet, firstFrame = camera.read() 28 if not firstRet: 29 print("Load video error!") 30 exit(0) 31 32 # 对第一帧进行预处理 33 firstFrame = imutils.resize(firstFrame, width=500) # 尺寸缩放,width=500 34 gray_firstFrame = cv2.cvtColor(firstFrame, cv2.COLOR_BGR2GRAY) # 灰度化 35 firstFrame = cv2.GaussianBlur(gray_firstFrame, (21, 21), 0) #高斯模糊,用于去噪 36 37 # 遍历视频的每一帧 38 while True: 39 (ret, frame) = camera.read() 40 41 # 如果没有获取到数据,则结束循环 42 if not ret: 43 break 44 45 # 对获取到的数据进行预处理 46 frame = imutils.resize(frame, width=500) 47 gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 48 gray_frame = cv2.GaussianBlur(gray_frame, (21, 21), 0) 49 50 # cv2.imshow('video', firstFrame) 51 # 计算第一帧和其他帧的差别 52 frameDiff = cv2.absdiff(firstFrame, gray_frame) 53 # 忽略较小的差别 54 retVal, thresh = cv2.threshold(frameDiff, 25, 255, cv2.THRESH_BINARY) 55 56 # 对阈值图像进行填充补洞 57 thresh = cv2.dilate(thresh, None, iterations=2) 58 image, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 59 60 text = "Unoccupied" 61 # 遍历轮廓 62 for contour in contours: 63 # if contour is too small, just ignore it 64 if cv2.contourArea(contour) < args["min_area"]: 65 continue 66 67 # 计算最小外接矩形(非旋转) 68 (x, y, w, h) = cv2.boundingRect(contour) 69 cv2.rectangle(frame, (x, y), (x+w, y+h), (0,255,0), 2) 70 text = "Occupied!" 71 72 cv2.putText(frame, "Room Status: {}".format(text), (10,20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 2) 73 74 cv2.imshow('frame', frame) 75 cv2.imshow('thresh', thresh) 76 cv2.imshow('frameDiff', frameDiff) 77 78 # 处理按键效果 79 key = cv2.waitKey(60) & 0xff 80 if key == 27: # 按下ESC时,退出 81 break 82 elif key == ord(' '): # 按下空格键时,暂停 83 cv2.waitKey(0) 84 85 # 释放资源并关闭所有窗口 86 camera.release() 87 cv2.destroyAllWindows()
附上原文实验结果: