python - 使用opencv删除任何图像的背景

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

<分区>

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

我使用了这个代码。

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)

但是这段代码只适用于这张图片

应该在代码中更改什么以使其适用于不同的图像

最佳答案

局部最优解

# 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. 问题

    不易处理背景与人脸颜色相似的情况。金色的头发和肤色使得很难用原始阈值找到正确的边缘。

    Max contour 是指当图像像测试图像中的围巾一样具有强而大的顶点时,很容易迷失某些区域。但这真的取决于你的人脸识别过程之后它是什么样的图像。

关于python - 使用opencv删除任何图像的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49093729/

相关文章:

python - 当它是 '' 时删除元组列表的元素

python-3.x - matplotlib.pyplot 具有等宽和紧凑布局的多边形

python - 求和函数在python中的使用

python - 从 Numpy Meshgrid 生成位置向量

python - 映射具有重复索引的数组?

python - Postgres `WITH ins AS ...` 将所有内容都转换为文本

python - 如何替换字符串中的成对标记?

python - 我如何才能可靠地访问一个太大而无法加载到内存中的 JSON 文件中的单个键值对?

python - 使用 python3 的列表生成器表达式中未定义全局,适用于 python2,需要进行哪些更改?

python-3.x - 由于 Mock 的 StopIteration 错误,Python 单元测试失败