python - 有没有直接的方法来裁剪图像中背景区域应该透明的不规则尺寸/非矩形对象
问题描述
我正在做对象检测,它给出了我想从原始图像中裁剪出来的特定多边形点,但除了感兴趣的区域之外,所有背景都应该是透明的(不仅仅是从 ROI 获得的 bitwise_and 操作后的黑色/白色)。想知道是否可以以这种方式裁剪它,而不是调整 alpha 值以降低背景的不透明度。
解决方案
这可以通过使用多边形点的 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)
结果:
推荐阅读
- php - 如何在 php 中使用 DateDiff 匹配日期间隔?
- c# - 将文本从一个表单上的文本框中复制到另一个表单上的标签
- sql-server - 在 ssis 中使用平面文件目标的多个工作表
- mysql - 计算另一个表中的时间戳小于/大于主表间隔的位置
- python - Django 错误 admin.E033:用户名不是 users.CustomUser 的属性。为什么我的自定义用户管理员不起作用?
- r - 如何在某些观察结果上运行函数?
- javascript - 注销后重定向 ajax 发布请求总是返回 401 并重定向到登录
- c - 字符数组和指针字符数组
- c# - Caesar Cipher C# - 如何正确解密
- php - Css 更改不适用于 php