python - 使用 OpenCV 删除图像的背景
问题描述
该代码适用于高分辨率图像。但有时当图像的分辨率不够好或背景颜色与图像中的颜色匹配时,它可以完全去除背景。有时,在移除的背景图像中留下白色斑块。以下是示例。在左边的原始图像上,在右边的图像上删除了背景图像。
输入图像
从下面的代码输出图像
期望的输出
右边是输入图像,右边是可以完全去除背景的代码的输出图像。
下面是描述使用 OpenCV 删除图像背景的过程的代码。
def remove_background(img):
#== Parameters =======================================================================
BLUR = 5
CANNY_THRESH_1 = 10
CANNY_THRESH_2 = 100
MASK_DILATE_ITER = 20
MASK_ERODE_ITER = 20
MASK_COLOR = (0.0,0.0,0.0) # In BGR format
#== Processing =======================================================================
#-- Read image -----------------------------------------------------------------------
img = cv2.imread(img)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#-- Edge detection -------------------------------------------------------------------
edges = cv2.Canny(gray, CANNY_THRESH_1, CANNY_THRESH_2)
edges = cv2.dilate(edges, None)
edges = cv2.erode(edges, None)
#-- Find contours in edges, sort by area ---------------------------------------------
contour_info = []
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
for c in contours:
contour_info.append((
c,
cv2.isContourConvex(c),
cv2.contourArea(c),
))
contour_info = sorted(contour_info, key=lambda c: c[2], reverse=True)
#-- Create empty mask, draw filled polygon on it corresponding to largest contour ----
# Mask is black, polygon is white
mask = np.zeros(edges.shape)
for c in contour_info:
cv2.fillConvexPoly(mask, c[0], (255))
# cv2.fillConvexPoly(mask, max_contour[0], (255))
#-- Smooth mask, then blur it --------------------------------------------------------
mask = cv2.dilate(mask, None, iterations=MASK_DILATE_ITER)
mask = cv2.erode(mask, None, iterations=MASK_ERODE_ITER)
mask = cv2.GaussianBlur(mask, (BLUR, BLUR), 0)
mask_stack = np.dstack([mask]*3) # Create 3-channel alpha mask
#-- Blend masked img into MASK_COLOR background --------------------------------------
mask_stack = mask_stack.astype('float32') / 255.0 # Use float matrices,
img = img.astype('float32') / 255.0 # for easy blending
masked = (mask_stack * img) + ((1 - mask_stack) * MASK_COLOR) # Blend
masked = (masked * 255).astype('uint8') # Convert back to 8-bit
cv2.imwrite('img.png', masked)
解决方案
推荐阅读
- angularjs - 空白页和 TypeError Angular Firebase
- azure-cosmosdb - EF Core 3.1 + Cosmos DB 和 Interceptor 可以一起工作吗?
- android - 如何在通过中介与各种广告网络一起使用 admob 时请求对个性化广告的同意?
- node.js - Laravel 7.9.2 “npm install” 安装了这么多文件
- javascript - 在 React 中使用 axios 在浏览器中显示来自 api 的对象数组
- reactjs - 如何通过graphql查询将br传递给内容属性或p标签内
- r - R访问矩阵到数组3d
- php - 无法存根或模拟类或接口“PhpOffice\PhpSpreadsheet\Worksheet\Worksheet”
- python - Python 脚本未从 crontab 执行
- python - 在 Python 中设置系统时钟?