使用场景

        一键抠图,但是,仅限于大面积背景的物品图片,本脚本主要是针对近白色背景的图片。

需要用到的库

import cv2
import numpy as np
from PIL import Image
import DwkCvShow

先定义背景的颜色范围(注意是HSV色彩空间的范围)

# 定义白色在HSV中的范围
# H(Hue)表示色调,范围是0-179;
# S(Saturation)表示饱和度,范围是0-255;
# V(Value)表示亮度,范围是0-255。
# lower_white = np.array([0, 0, 168])
lower_white = np.array([0, 0, 150])
upper_white = np.array([172, 111, 255])

读取图片并且转换成HSV颜色空间

# 读取图片
img = cv2.imread('./input/002.jpg')

# 将BGR图像转换为HSV图像
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
print("转换成hsv色彩空间")
DwkCvShow.resize_and_show_image(hsv)

创建白色掩码并且降噪处理

# 创建一个白色的掩码
mask = cv2.inRange(hsv, lower_white, upper_white)
# 定义结构元素
kernel = np.ones((5, 5), np.uint8)
print("创建一个白色掩码")
DwkCvShow.resize_and_show_image(mask)

# 先腐蚀
eroded = cv2.erode(mask, kernel, iterations=2)
print("创建一个白色掩码先腐蚀")
DwkCvShow.resize_and_show_image(eroded)

# 再膨胀
dilated = cv2.dilate(eroded, kernel, iterations=2)
print("创建一个白色掩码先腐蚀再膨胀")
DwkCvShow.resize_and_show_image(dilated)

反转掩码并且降噪处理

# 反转掩码:将白色变为黑色,将黑色变为白色
mask_inv = cv2.bitwise_not(dilated)
print("反转掩码")
DwkCvShow.resize_and_show_image(mask_inv)

# 定义结构元素
kernel = np.ones((5, 5), np.uint8)

# 先腐蚀
eroded = cv2.erode(mask_inv, kernel, iterations=2)
print("反转掩码后先腐蚀")
DwkCvShow.resize_and_show_image(eroded)
# 再膨胀
dilated = cv2.dilate(eroded, kernel, iterations=2)
print("反转掩码后先腐蚀再膨胀")
DwkCvShow.resize_and_show_image(dilated)

绘制产品物品的最大轮廓

# 最终二值图
# 找到所有轮廓
contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 找到最大的轮廓
max_contour = max(contours, key=cv2.contourArea)
# # 使用Douglas-Peucker算法来平滑轮廓
# epsilon = 0.005*cv2.arcLength(max_contour, True)
# approx = cv2.approxPolyDP(max_contour, epsilon, True)

# 创建一个全黑的背景,大小和原图像一样
background = np.zeros_like(dilated)

# 在黑色背景上绘制白色的最大轮廓
# cv2.drawContours(background, [approx], -1, (255), thickness=cv2.FILLED)
cv2.drawContours(background, [max_contour], -1, (255), thickness=cv2.FILLED)
DwkCvShow.resize_and_show_image(background)

抠图并且保存图片

# 使用反转的掩码移除背景
res = cv2.bitwise_and(img, img, mask=background)
print("白色的掩码反转后移除背景")
print("准备写入新的图像")
DwkCvShow.resize_and_show_image(res)

# 将OpenCV图像转换为PIL图像
res = cv2.cvtColor(res, cv2.COLOR_BGR2RGB)
pil_img = Image.fromarray(res)

# 创建一个新的透明背景图像
transparent_img = Image.new("RGBA", pil_img.size)
for x in range(pil_img.width):
    for y in range(pil_img.height):
        r, g, b = pil_img.getpixel((x, y))
        if (r, g, b) != (0, 0, 0):
            transparent_img.putpixel((x, y), (r, g, b, 255))

# 保存透明背景图像
transparent_img.save('颜色掩码方法+轮廓绘制.png', 'PNG')

总结

        简单的算法是很难实现平滑抠图的,需要用到高等数学。大概的方向是计算曲线前面部分导数(当然不仅仅是导数,总之跟曲线的末端切线方向有关)。

02-29 07:15