我已经使用背景减去技术创建了一个分割。下一步我想做的是消除像素数量小于20的前景区域。问题是如何计算一帧中每个前景区域的像素数量?example frame
发布于 2021-11-23 20:10:40
您可以使用findContours
和contourArea
。如下所示:
import cv2 as cv
import numpy as np
# change 0 to 1 for shadow detection
backSub = cv.createBackgroundSubtractorMOG2(500,16,0)
capture = cv.VideoCapture("path/to/video.mp4")
if not capture.isOpened():
print('Unable to open video')
exit(0)
while True:
ret, frame = capture.read()
if frame is None:
break
fgMask = backSub.apply(frame)
cv.rectangle(frame, (10, 2), (100,20), (255,255,255), -1)
# this part is what you are looking for:
contours, hierarchy = cv.findContours(fgMask, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
# create an empty mask
mask = np.zeros(frame.shape[:2],dtype=np.uint8)
# loop through the contours
for i,cnt in enumerate(contours):
# if the size of the contour is greater than a threshold
if cv.contourArea(cnt) > 20:
cv.drawContours(mask,[cnt], 0, (255), -1)
cv.imshow('Frame', frame)
cv.imshow('FG Mask', fgMask)
cv.imshow("Mask", mask)
keyboard = cv.waitKey(30)
if keyboard == 'q' or keyboard == 27:
break
https://stackoverflow.com/questions/69882008
复制相似问题