赞
踩
cv2.getStructuringElement(shape, ksize, anchor) -> retval
返回进行形态操作后,指定大小和形状的元素,其中
MORPH_RECT: 长方形结构元素
MORPH_ELLIPSE: 椭圆结构元素,即内接矩形Rect(0, 0, esize.width, esize.height)中的填充椭圆
MORPH_CROSS: 十字形结构元素
CV_SHAPE_CUSTOM: 自定义结构元素(OpenCV 1.x API)
cv2.absdiff(src1, src2, dst) -> dst
计算两个数组 或 数组与标量 之间的每元素差的绝对值。其中
- import cv2 as cv
- import numpy as np
-
- camera = cv.VideoCapture("D:/Temp/python_project/test_data/video/snow.mp4")
- es = cv.getStructuringElement(cv.MORPH_ELLIPSE, (9,4))
- kernel = np.ones((5,5), np.uint8)
- background = None
- while (True):
- ret, frame = camera.read()
- if ret:
- frame = cv.flip(frame, 1)
- img = frame
-
- if background is None:
- background = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
- background = cv.GaussianBlur(background, (21, 21), 0)
- continue
- gray_frame = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
- gray_frame = cv.GaussianBlur(gray_frame, (21, 21), 0)
- diff = cv.absdiff(background, gray_frame)
- diff = cv.threshold(diff, 25, 255, cv.THRESH_BINARY)[1]
- diff = cv.dilate(diff, es, kernel, iterations=2)
- cnts, hierarchy = cv.findContours(diff.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
- for c in cnts:
- if cv.contourArea(c) < 1500:
- continue
- (x, y, w, h) = cv.boundingRect(c)
- cv.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
- cv.imshow("contours", img)
- cv.imshow("dif", diff)
- cv.waitKey(10)
- else:
- break
- cv.destroyAllWindows()
- camera.release()

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。