如何从此类图像中移除背景?

2024-05-23 19:15:44 发布

您现在位置:Python中文网/ 问答频道 /正文

Image_1

我想删除此图像的背景,只获取此人。我有上千张这样的照片,基本上,是一个人和一个有点苍白的背景。

我所做的是使用边缘检测器,比如canny边缘检测器或sobel过滤器(来自skimage库)。然后我想可以做的是,把边缘内的像素变白,把边缘外的像素变黑。之后,可以对原始图像进行遮罩,只得到人的照片。

然而,用canny边缘检测器很难得到一个封闭的边界。结果使用Sobel过滤器并没有那么糟糕,但是我不知道如何从那里着手。

Sobel_result

编辑:

是否也可以删除右手和裙子之间以及头发之间的背景?


Tags: 图像编辑过滤器像素照片检测器边缘边界
3条回答

作为替代方案,您可以使用类似这样的神经网络:CRFRNN

结果是这样的:

enter image description here

下面的代码将帮助您开始。您可能需要使用程序顶部的参数来微调提取:

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


#== Processing =======================================================================

#-- Read image -----------------------------------------------------------------------
img = cv2.imread('C:/Temp/person.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)
# Previously, for a previous version of cv2, this line was: 
#  contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
# Thanks to notes from commenters, I've updated the code but left this note
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          # 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.imshow('img', masked)                                   # Display
cv2.waitKey()

#cv2.imwrite('C:/Temp/person-masked.jpg', masked)           # Save

输出: enter image description here

如果希望不使用红色填充背景,但使其透明,可以向解决方案中添加以下行:

# split image into channels
c_red, c_green, c_blue = cv2.split(img)

# merge with mask got on one of a previous steps
img_a = cv2.merge((c_red, c_green, c_blue, mask.astype('float32') / 255.0))

# show on screen (optional in jupiter)
%matplotlib inline
plt.imshow(img_a)
plt.show()

# save to disk
cv2.imwrite('girl_1.png', img_a*255)

# or the same using plt
plt.imsave('girl_2.png', img_a)

如果你想,你可以调整一些png压缩参数,使文件更小。

图片在下面的白色背景上。或者是黑色的-http://imgur.com/a/4NwmH

enter image description here

相关问题 更多 >