NumPy/OpenCV 2:如何裁剪非矩形区域?

ffr*_*end 32 python opencv numpy image-processing

我有一组形成一个形状的点(闭合折线).现在我想从这个形状内的一些图像中复制/裁剪所有像素,剩下的就是黑色/透明.我该怎么做呢?

例如,我有这个:

在此输入图像描述

我想得到这个:

在此输入图像描述

Kob*_*ohn 52

*编辑 - 更新以处理具有Alpha通道的图像.

这对我有用:

  • 制作一个全黑的面具(全部蒙面)
  • 使用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)
Run Code Online (Sandbox Code Playgroud)

  • @kju这看起来有限,我刚刚更新了答案,而不是提出一个新问题.我想很多人这样做可能也想要一个透明的面具. (3认同)
  • 如果您的形状是凸多边形,您应该使用 `cv2.fillConvexPoly`。[文档](http://docs.opencv.org/3.0-beta/modules/imgproc/doc/drawing_functions.html#fillconvexpoly) 指出这种方法比 `cv2.fillPoly`“快得多”。 (2认同)

Kan*_*hew 7

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

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)
Run Code Online (Sandbox Code Playgroud)

输入图像: 输入图像

面具图片: 蒙版图像

结果输出图像: 在此处输入图片说明