【问题标题】:How to mask a video frame using contours with opencv in python如何在python中使用带有opencv的轮廓屏蔽视频帧
【发布时间】:2015-07-13 13:05:57
【问题描述】:

我在 python 中使用 opencv(cv2 模块)来识别视频中的对象。在每一帧中,我想提取一个特定的区域,也就是轮廓。向opencv docs学习后,我有如下代码sn-p:

        # np is numpy module, contours are expected results,
        # frame is each frame of the video

        # Iterate through the contours.
        for contour in contours:
            # Compute the bounding box for the contour, draw
            # it on the frame, and update the text.
            x, y, w, h = cv2.boundingRect(contour)

            # Find the mask and build a histogram for the object.
            mask = np.zeros(frame.shape[:2], np.uint8)
            mask[y:h, x:w] = 255
            masked_img = cv2.bitwise_and(frame, frame, mask = mask)
            obj_hist = cv2.calcHist([masked_img], [0], None, [256], [0, 256])

但是,当我使用matplotlib 显示masked_img 时,它会返回一个暗图像。 obj_hist 只有一个元素的编号大于0,这是第一个。怎么了?

【问题讨论】:

  • @boardrider 我已经编辑了它,希望这可以帮助你理解我的问题:-)
  • 您确认contours 包含任何内容了吗?
  • @MikeC 是的,contours 很好,我可以用它检测新对象。但我未能提取特定区域

标签: python opencv image-processing matplotlib


【解决方案1】:

问题在于您在掩码中设置值的方式。特别是这一行:

mask[y:h, x:w] = 255

您正试图通过使用y:hx:w 设置蒙版来切入图像的每个维度。冒号左边是起始行或列,冒号右边表示结束行或列。鉴于您从y 开始,您需要使用相同的引用yh偏移...xw 也是如此。

在冒号的右侧值小于左侧的情况下进行切片不会以任何方式修改数组,这就是您没有得到任何输出的主要原因,因为当掩码最初全为零时您没有修改掩码.

你可能打算这样做:

mask[y:y+h, x:x+w] = 255

这会将cv2.boundingRect 给出的正确区域正确设置为白色 (255)。

【讨论】:

    猜你喜欢
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2018-07-20
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多