【问题标题】:NumPy/OpenCV 2: how do I crop non-rectangular region?NumPy/OpenCV 2:如何裁剪非矩形区域?
【发布时间】:2013-02-26 19:17:32
【问题描述】:

我有一组构成形状(闭合折线)的点。现在我想从 此形状内 的某个图像中复制/裁剪所有像素,其余部分为黑色/透明。我该怎么做呢?

例如,我有这个:

我想得到这个:

【问题讨论】:

  • 我相信您会希望使用不规则的 ROI(感兴趣区域)。你可以从这里开始:stackoverflow.com/questions/10632195/…
  • 以防万一:这个问题不是重复的,因为提到的一个描述的是 C API 而不是 Python(不过,这个问题仍然很有帮助)。

标签: python opencv image-processing numpy


【解决方案1】:

*edit - 已更新以处理具有 Alpha 通道的图像。

这对我有用:

  • 制作一个全黑的蒙版(全蒙版)
  • 按照 ROI 的形状用白色填充多边形
  • 将蒙版和您的图像结合起来,以获得黑色的 ROI

对于接受掩码的函数,您可能只想将图像和掩码分开。但是,我相信这可以满足您的具体要求:

import cv2
import numpy as np

# original image
# -1 loads as-is so if it will be 3 or 4 channel as the original
image = cv2.imread('image.png', -1)
# mask defaulting to black for 3-channel and transparent for 4-channel
# (of course replace corners with yours)
mask = np.zeros(image.shape, dtype=np.uint8)
roi_corners = np.array([[(10,10), (300,300), (10,300)]], dtype=np.int32)
# fill the ROI so it doesn't get wiped out when the mask is applied
channel_count = image.shape[2]  # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,)*channel_count
cv2.fillPoly(mask, roi_corners, ignore_mask_color)
# from Masterfool: use cv2.fillConvexPoly if you know it's convex

# apply the mask
masked_image = cv2.bitwise_and(image, mask)

# save the result
cv2.imwrite('image_masked.png', masked_image)

【讨论】:

  • @kobejohn 创建蒙版以使用此裁剪制作透明背景?
  • @kju 你的意思是你想要透明而不是 ROI 之外的黑色吗?
  • @kju 这似乎很有限,我只是更新了答案而不是提出新问题。我想很多这样做的人可能也想要一个透明的面具。
  • 如果你的形状是凸多边形,你应该使用cv2.fillConvexPolyThe documentation 表示此方法比 cv2.fillPoly“快得多”。
  • 对于我的 fillPoly 没有工作,但 fillConvexPoly 有。谢谢@Masterfool
【解决方案2】:

以下代码有助于裁剪图像并将它们置于白色背景中。

import cv2
import numpy as np

# load the image
image_path = 'input image path'
image = cv2.imread(image_path)

# create a mask with white pixels
mask = np.ones(image.shape, dtype=np.uint8)
mask.fill(255)

# points to be cropped
roi_corners = np.array([[(0, 300), (1880, 300), (1880, 400), (0, 400)]], dtype=np.int32)
# fill the ROI into the mask
cv2.fillPoly(mask, roi_corners, 0)

# The mask image
cv2.imwrite('image_masked.png', mask)

# applying th mask to original image
masked_image = cv2.bitwise_or(image, mask)

# The resultant image
cv2.imwrite('new_masked_image.png', masked_image)

输入图像:

蒙版图片:

结果输出图像:

【讨论】:

  • 这与接受的答案非常相似。你能解释一下这如何增加这个问题的价值吗?
  • 以下代码有助于获取白色背景蒙版图像而不是黑色。
  • 这不会添加任何新内容。只需反转面具。
  • 从第一个答案开始,如果您可以创建一个倒置的掩码并能够提供相同的结果,将会很有帮助。
  • 我很欣赏这条评论,因为它有代表性的图片。
猜你喜欢
  • 1970-01-01
  • 2017-06-01
  • 2015-10-18
  • 2014-02-03
  • 1970-01-01
  • 1970-01-01
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多