代码: detect.py
#coding=gbk
import cv2
import numpy as np
camera = cv2.VideoCapture(0)
#构造一个椭圆形结构元素,关于cv2.getStructuringElement()函数可自行百度
es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(9,4))
kernel = np.ones((5,5),np.uint8)
background = None
while Ture:
ret, frame = camera.read()
if background is None:
background = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
background = cv2.GaussianBlur(background,(21,21),0)
continue #结合while、for循环使用,意思为跳过后续的代码段,接在后面的代码不执行
gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
gray_frame = cv2.GaussianBlur(gray_frame,(21,21),0)
diff = cv2.absdiff(background,gray_frame) #将读取的帧与背景图相减
diff = cv2.threshold(diff,25,255,cv2.THRESH_BINARY)[1] # 进行二值化处理,只显示白色和黑色两色图像
diff = cv2.dilate(diff,es,iteration = 2)
#cv2.findContours()函数找出边界,具体参数含义可百度,返回三个值,cnts表示边界的数量
image,cnts,hierarchy = cv2.findContours(diff.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
if cv2.contoursArea(c)<1500: # 函数cv2.contoursArea()求解边界面积
continue
(x,y,w,h) = cv2.boundingRect(c) # 获取直边界矩形
cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 255, 0), 2)
cv2.imshow("mog", fgmask)
cv2.imshow("thresh", th)
k = cv2.waitKey(30) & 0xff
if k == 27: # 退出按ESC键
break
camera.release()
cv2.destroyAllWindows()
代码虽短,但涉及的知识点较多, 如:cv2.getStructuringElement()、cv2.absdiff()、cv2.threshold()[1](二值化处理会返回多个值,用索引[1]表示返回二值化处理后的图像)、cv2.dilate()(膨胀图像处理,另还有腐蚀图像处理cv2.erode())、cv2.findContours()、cv2.contoursArea()、cv2.boundingRect()可一一百度学习。