首页 > 解决方案 > 有没有直接的方法来裁剪图像中背景区域应该透明的不规则尺寸/非矩形对象

问题描述

我正在做对象检测,它给出了我想从原始图像中裁剪出来的特定多边形点,但除了感兴趣的区域之外,所有背景都应该是透明的(不仅仅是从 ROI 获得的 bitwise_and 操作后的黑色/白色)。想知道是否可以以这种方式裁剪它,而不是调整 alpha 值以降低背景的不透明度。

标签: pythonopencvimage-processingpolygoncrop

解决方案


这可以通过使用多边形点的 fillPoly() 在 Python/OpenCV 中的黑色背景上制作白色填充蒙版来完成。然后将蒙版放入图像的alpha通道。

输入:

在此处输入图像描述

import cv2
import numpy as np

# read image
img = cv2.imread("efile.jpg")

points = np.array( [[ [693,67], [23,85], [62,924], [698,918] ]] )

# draw white filled polygon from points on black background as mask
mask = np.zeros_like(img)
cv2.fillPoly(mask, points, (255,255,255))
mask = mask[:,:,0]

# put mask into alpha channel of image
result = img.copy()
result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
result[:,:,3] = mask

# write results
cv2.imwrite("efile_mask.jpg", mask)
cv2.imwrite("efile_transparent.png", result)

# display it
cv2.imshow("efile_mask", mask)
cv2.imshow("efile_transparent", result)
cv2.waitKey(0)

结果:

在此处输入图像描述


推荐阅读