使用opencv删除任何图像的背景 [英] remove background of any image using opencv

查看:261
本文介绍了使用opencv删除任何图像的背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been searching for a technique to remove the background of a any given image. The idea is to detect a face and remove the background of the detected face. I have finished the face part. Now removing the background part still exists.

我使用了这段代码.

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)

但是此代码仅适用于该图片

But this code only works for only this image

使用不同的图片代码应更改为

What should be changed into to use the code for different images

推荐答案

本地最佳解决方案

# 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))

效果

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

      • Test Image
        • Similar color of background, hair and skin
          • 原始输出
            • 原始输出
            • Original Output
              • original output

              • 原始边缘

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

              • Apply all contour rather than max contour with same edge threshold

              • 稍微好一点

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

              Canny Thresh 2 set as 100, apply all contour

              • 好多了

              • 更强的边缘

              • Canny Thresh 2设置为40,应用所有轮廓
                • 边缘开始变得不那么锋利
                • Canny Thresh 2 set as 40, apply all contour
                  • edges starts to become not so sharp

                  1. 程序行为

                  1. Program Behavior

                  程序搜索边缘并建立轮廓.获取最大轮廓并识别为人脸.然后涂上口罩.

                  The program searches edges and builds contours. Get the max contour and recognize as human face. Then apply mask.

                  问题

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

                  Not easy to deal with similar color between background and human face. Blond hair and skin color makes it's hard to find correct edges with the original threshold.

                  最大轮廓线意味着当图像具有强而大的顶点(如测试图像中的围巾)时,很容易丢失某些区域的轨迹.但这实际上取决于人脸识别过程后的图像类型.

                  Max contour means when images have strong and big vertex like the scarf in test image, it's easy to lose track of some area. But it really depends on what kind of image it is after your human face recognition process.

                  这篇关于使用opencv删除任何图像的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆