python --去除人像背景(抠图)

方法一

注册

https://www.remove.bg/zh/api#api-reference

实操

import time
import requests
import win32ui
import pyautogui
import PySimpleGUI as sg
import os

a = pyautogui.confirm(text='是否现在开始去除人像背景', title='小毅欧巴', buttons=['开始', '关闭'])
if a == '关闭':
    exit()

dlg = win32ui.CreateFileDialog(1)  # 参数 1 表示打开文件对话框
dlg.SetOFNInitialDir('C:')  # 设置打开文件对话框中的初始显示目录
dlg.DoModal()
filename = dlg.GetPathName()
file, ext = os.path.splitext(filename)
if ext not in ('.jpg', '.JPG', '.PNG', '.png'):
    pyautogui.alert(text='文件仅支持(jpg, png)', title='提示', button='关闭')
    exit()

pyautogui.alert(text=filename, title='确认路径', button='我已确认')

key = 'c6vLHWNS7fDFAvoMXk3uo4mB'
# rmbg = RemoveBg(key, "error.log")
# rmbg.remove_background_from_img_file(filename)
new_file_name = os.path.join(os.path.join(os.path.expanduser('~'), "Desktop"), 'no-bg.png')
with open(filename, 'rb') as f:
    response = requests.post(
        'https://api.remove.bg/v1.0/removebg',
        files={'image_file': f},
        data={
            'size': "regular",
            'bg_color': None
        },
        headers={'X-Api-Key': key})
    with open(new_file_name, 'wb') as removed_bg_file:
        removed_bg_file.write(response.content)

mylist = [1, 2, 3, 4, 5, 6, 7, 8]
for i, item in enumerate(mylist):
    sg.one_line_progress_meter('AI', i + 1, len(mylist), '正在智能清除背景')
    time.sleep(0.1)

方法二

# OpenCV 人像分割
```python
import cv2

# 加载模型
net = cv2.dnn.readNetFromCaffe("model.prototxt", "model.caffemodel")

# 加载图片
image = cv2.imread("image.jpg")

# 执行人像分割
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
net.setInput(blob)
output = net.forward()
h, w = image.shape[:2]

# 遍历分割结果,抠出人像
for i in range(output.shape[2]):
confidence = output[0, 0, i, 2]

if confidence > 0.5:
box = output[0, 0, i, 3:7] * np.array([w, h, w, h])
start_x, start_y, end_x, end_y = box.astype("int")

# 确保人像在原图内
start_x, start_y = max(start_x, 0), max(start_y, 0)
end_x, end_y = min(end_x, w - 1), min(end_y, h - 1)

# 抠出人像
roi = image[start_y:end_y, start_x:end_x].copy()

方法三

基于深度学习的人像分割

import numpy as np
import tensorflow as tf
from PIL import Image

# 加载模型和预处理器
model = tf.keras.models.load_model('model.h5')
preprocessor = tf.keras.applications.mobilenet_v2.preprocess_input

# 加载图片
image = Image.open('image.jpg')

# 预处理图片
inputs = preprocessor(np.array(image.resize((224, 224))))

# 执行人像分割
mask = model.predict(np.array([inputs]))[0]

# 处理分割结果,抠出人像
mask = np.array(Image.fromarray((mask * 255).astype('uint8')).resize(image.size))
mask = np.stack([mask, mask, mask], axis=-1)
roi = np.where(mask > 128, image, 0)

你可能感兴趣的:(笔记,python,开发语言,后端)