如何在 python 中使用带有 opencv 的轮廓来屏蔽视频帧
How to mask a video frame using contours with opencv in python
我在 python 中使用 opencv(cv2 模块)来识别视频中的对象。在每一帧中,我想提取一个特定的区域,也就是轮廓。在向 opencv docs 学习后,我有以下代码片段:
# 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
时,它 returns 是一个暗图像。 obj_hist
只有一个元素的个数大于0
,也就是第一个。怎么了?
问题在于您在掩码中设置值的方式。具体这一行:
mask[y:h, x:w] = 255
您正在尝试通过使用 y:h
和 x:w
设置遮罩来切入图像的每个维度。冒号左边是起始行或列,冒号右边表示end行或列。鉴于您从 y
开始,您需要使用相同的参考 y
offset 到 h
... [=17] 也是如此=] 和 w
.
在冒号右边的值小于左边的值的地方进行切片不会以任何方式修改数组,这就是为什么你没有得到任何输出的主要原因,因为你没有在最初修改掩码时全为零。
您可能打算这样做:
mask[y:y+h, x:x+w] = 255
这会将 cv2.boundingRect
给出的正确区域正确设置为白色 (255)。
我在 python 中使用 opencv(cv2 模块)来识别视频中的对象。在每一帧中,我想提取一个特定的区域,也就是轮廓。在向 opencv docs 学习后,我有以下代码片段:
# 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
时,它 returns 是一个暗图像。 obj_hist
只有一个元素的个数大于0
,也就是第一个。怎么了?
问题在于您在掩码中设置值的方式。具体这一行:
mask[y:h, x:w] = 255
您正在尝试通过使用 y:h
和 x:w
设置遮罩来切入图像的每个维度。冒号左边是起始行或列,冒号右边表示end行或列。鉴于您从 y
开始,您需要使用相同的参考 y
offset 到 h
... [=17] 也是如此=] 和 w
.
在冒号右边的值小于左边的值的地方进行切片不会以任何方式修改数组,这就是为什么你没有得到任何输出的主要原因,因为你没有在最初修改掩码时全为零。
您可能打算这样做:
mask[y:y+h, x:x+w] = 255
这会将 cv2.boundingRect
给出的正确区域正确设置为白色 (255)。