【问题标题】:remove background of any image using opencv使用opencv删除任何图像的背景
【发布时间】:2018-08-12 02:53:46
【问题描述】:

我一直在寻找一种技术来去除任何给定图像的背景。这个想法是检测人脸并去除检测到的人脸的背景。我已经完成了面部部分。现在去掉背景部分依然存在。

我使用了这个代码。

import cv2
import numpy as np

#== Parameters           
BLUR = 21
CANNY_THRESH_1 = 10
CANNY_THRESH_2 = 200
MASK_DILATE_ITER = 10
MASK_ERODE_ITER = 10
MASK_COLOR = (0.0,0.0,1.0) # In BGR format


#-- Read image
img = cv2.imread('SYxmp.jpg')
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)
max_contour = contour_info[0]

#-- Create empty mask, draw filled polygon on it corresponding to largest contour ----
# Mask is black, polygon is white
mask = np.zeros(edges.shape)
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         
img         = img.astype('float32') / 255.0    
masked = (mask_stack * img) + ((1-mask_stack) * MASK_COLOR)  
masked = (masked * 255).astype('uint8')                    

cv2.imshow('img', masked)                                   # Display
cv2.waitKey()
cv2.imwrite("WTF.jpg",masked)

但此代码仅适用于此图像

为不同的图片使用代码应该改成什么

【问题讨论】:

  • 检测到的人脸的背景是什么?
  • @YvesDaoust 我只需要将脸部保存为透明的 png 文件。例如,一旦检测到人脸,我希望将人脸直接保存为没有背景的透明png文件

标签: python python-3.x numpy opencv image-processing


【解决方案1】:

局部最优解

# Original Code
CANNY_THRESH_2 = 200

# Change to
CANNY_THRESH_2 = 100

####### Change below worth to try but not necessary

# Original Code
mask = np.zeros(edges.shape)
cv2.fillConvexPoly(mask, max_contour[0], (255))

# Change to
for c in contour_info:
    cv2.fillConvexPoly(mask, c[0], (255))

效果

  • 测试图像
    • 背景、头发和皮肤的颜色相似

  • 原始输出
    • 原始输出

  • 原始边缘

  • 应用所有轮廓而不是具有相同边缘阈值的最大轮廓

    • 稍微好一点

  • Canny Thresh 2 设置为 100,应用所有轮廓

    • 好多了

  • 更强的边缘

  • Canny Thresh 2 设置为 40,应用所有轮廓
    • 边缘开始变得不那么锋利了

推理

  1. 程序行为

    程序搜索边缘并构建轮廓。获取最大轮廓并识别为人脸。然后敷面膜。

  2. 问题

    不容易处理背景和人脸之间的相似颜色。金色的头发和肤色使得很难找到具有原始阈值的正确边缘。

    最大轮廓是指当测试图像中有像围巾这样的大顶点时,很容易丢失某些区域。但这真的取决于你的人脸识别过程之后是什么样的图像。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 2020-12-05
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    相关资源
    最近更新 更多