首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何计算背景差分中前景区域的像素数

如何计算背景差分中前景区域的像素数
EN

Stack Overflow用户
提问于 2021-11-08 10:29:25
回答 1查看 40关注 0票数 0

我已经使用背景减去技术创建了一个分割。下一步我想做的是消除像素数量小于20的前景区域。问题是如何计算一帧中每个前景区域的像素数量?example frame

EN

回答 1

Stack Overflow用户

发布于 2021-11-23 20:10:40

您可以使用findContourscontourArea。如下所示:

代码语言:javascript
运行
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69882008

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档