Spaces:
Running
Running
File size: 13,847 Bytes
ca46a75 06fbec3 ca46a75 4be6b70 1c25fe3 06fbec3 4be6b70 ca46a75 1d213d9 1c25fe3 06fbec3 1c25fe3 06fbec3 1c25fe3 1d213d9 1c25fe3 06fbec3 1c25fe3 ca46a75 4be6b70 2c368dd 4be6b70 ca46a75 1c25fe3 ca46a75 1c25fe3 06fbec3 ca46a75 06fbec3 1c25fe3 06fbec3 ca46a75 06fbec3 ca46a75 06fbec3 ca46a75 1c25fe3 2c368dd 1c25fe3 06fbec3 1c25fe3 06fbec3 1c25fe3 06fbec3 1c25fe3 06fbec3 2c368dd 1d213d9 06fbec3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""
@DATE: 2024/9/5 21:21
@File: human_matting.py
@IDE: pycharm
@Description:
人像抠图
"""
import numpy as np
from PIL import Image
import onnxruntime
from .tensor2numpy import NNormalize, NTo_Tensor, NUnsqueeze
from .context import Context
import cv2
import os
from time import time
WEIGHTS = {
"hivision_modnet": os.path.join(
os.path.dirname(__file__), "weights", "hivision_modnet.onnx"
),
"modnet_photographic_portrait_matting": os.path.join(
os.path.dirname(__file__),
"weights",
"modnet_photographic_portrait_matting.onnx",
),
"mnn_hivision_modnet": os.path.join(
os.path.dirname(__file__),
"weights",
"mnn_hivision_modnet.mnn",
),
"rmbg-1.4": os.path.join(os.path.dirname(__file__), "weights", "rmbg-1.4.onnx"),
"birefnet-v1-lite": os.path.join(
os.path.dirname(__file__), "weights", "birefnet-v1-lite.onnx"
),
}
ONNX_DEVICE = onnxruntime.get_device()
ONNX_PROVIDER = (
"CUDAExecutionProvider" if ONNX_DEVICE == "GPU" else "CPUExecutionProvider"
)
HIVISION_MODNET_SESS = None
MODNET_PHOTOGRAPHIC_PORTRAIT_MATTING_SESS = None
RMBG_SESS = None
BIREFNET_V1_LITE_SESS = None
def load_onnx_model(checkpoint_path, set_cpu=False):
providers = (
["CUDAExecutionProvider", "CPUExecutionProvider"]
if ONNX_PROVIDER == "CUDAExecutionProvider"
else ["CPUExecutionProvider"]
)
if set_cpu:
sess = onnxruntime.InferenceSession(
checkpoint_path, providers=["CPUExecutionProvider"]
)
else:
try:
sess = onnxruntime.InferenceSession(checkpoint_path, providers=providers)
except Exception as e:
if ONNX_DEVICE == "CUDAExecutionProvider":
print(f"Failed to load model with CUDAExecutionProvider: {e}")
print("Falling back to CPUExecutionProvider")
# 尝试使用CPU加载模型
sess = onnxruntime.InferenceSession(
checkpoint_path, providers=["CPUExecutionProvider"]
)
else:
raise e # 如果是CPU执行失败,重新抛出异常
return sess
def extract_human(ctx: Context):
"""
人像抠图
:param ctx: 上下文
"""
# 抠图
matting_image = get_modnet_matting(ctx.processing_image, WEIGHTS["hivision_modnet"])
# 修复抠图
ctx.processing_image = hollow_out_fix(matting_image)
ctx.matting_image = ctx.processing_image.copy()
def extract_human_modnet_photographic_portrait_matting(ctx: Context):
"""
人像抠图
:param ctx: 上下文
"""
# 抠图
matting_image = get_modnet_matting_photographic_portrait_matting(
ctx.processing_image, WEIGHTS["modnet_photographic_portrait_matting"]
)
# 修复抠图
ctx.processing_image = matting_image
ctx.matting_image = ctx.processing_image.copy()
def extract_human_mnn_modnet(ctx: Context):
matting_image = get_mnn_modnet_matting(
ctx.processing_image, WEIGHTS["mnn_hivision_modnet"]
)
ctx.processing_image = hollow_out_fix(matting_image)
ctx.matting_image = ctx.processing_image.copy()
def extract_human_rmbg(ctx: Context):
matting_image = get_rmbg_matting(ctx.processing_image, WEIGHTS["rmbg-1.4"])
ctx.processing_image = matting_image
ctx.matting_image = ctx.processing_image.copy()
# def extract_human_birefnet_portrait(ctx: Context):
# matting_image = get_birefnet_portrait_matting(
# ctx.processing_image, WEIGHTS["birefnet-portrait"]
# )
# ctx.processing_image = matting_image
# ctx.matting_image = ctx.processing_image.copy()
def extract_human_birefnet_lite(ctx: Context):
matting_image = get_birefnet_portrait_matting(
ctx.processing_image, WEIGHTS["birefnet-v1-lite"]
)
ctx.processing_image = matting_image
ctx.matting_image = ctx.processing_image.copy()
def hollow_out_fix(src: np.ndarray) -> np.ndarray:
"""
修补抠图区域,作为抠图模型精度不够的补充
:param src:
:return:
"""
b, g, r, a = cv2.split(src)
src_bgr = cv2.merge((b, g, r))
# -----------padding---------- #
add_area = np.zeros((10, a.shape[1]), np.uint8)
a = np.vstack((add_area, a, add_area))
add_area = np.zeros((a.shape[0], 10), np.uint8)
a = np.hstack((add_area, a, add_area))
# -------------end------------ #
_, a_threshold = cv2.threshold(a, 127, 255, 0)
a_erode = cv2.erode(
a_threshold,
kernel=cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
iterations=3,
)
contours, hierarchy = cv2.findContours(
a_erode, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE
)
contours = [x for x in contours]
# contours = np.squeeze(contours)
contours.sort(key=lambda c: cv2.contourArea(c), reverse=True)
a_contour = cv2.drawContours(np.zeros(a.shape, np.uint8), contours[0], -1, 255, 2)
# a_base = a_contour[1:-1, 1:-1]
h, w = a.shape[:2]
mask = np.zeros(
[h + 2, w + 2], np.uint8
) # mask 必须行和列都加 2,且必须为 uint8 单通道阵列
cv2.floodFill(a_contour, mask=mask, seedPoint=(0, 0), newVal=255)
a = cv2.add(a, 255 - a_contour)
return cv2.merge((src_bgr, a[10:-10, 10:-10]))
def image2bgr(input_image):
if len(input_image.shape) == 2:
input_image = input_image[:, :, None]
if input_image.shape[2] == 1:
result_image = np.repeat(input_image, 3, axis=2)
elif input_image.shape[2] == 4:
result_image = input_image[:, :, 0:3]
else:
result_image = input_image
return result_image
def read_modnet_image(input_image, ref_size=512):
im = Image.fromarray(np.uint8(input_image))
width, length = im.size[0], im.size[1]
im = np.asarray(im)
im = image2bgr(im)
im = cv2.resize(im, (ref_size, ref_size), interpolation=cv2.INTER_AREA)
im = NNormalize(im, mean=np.array([0.5, 0.5, 0.5]), std=np.array([0.5, 0.5, 0.5]))
im = NUnsqueeze(NTo_Tensor(im))
return im, width, length
def get_modnet_matting(input_image, checkpoint_path, ref_size=512):
global HIVISION_MODNET_SESS
if not os.path.exists(checkpoint_path):
print(f"Checkpoint file not found: {checkpoint_path}")
return None
if HIVISION_MODNET_SESS is None:
HIVISION_MODNET_SESS = load_onnx_model(checkpoint_path, set_cpu=True)
input_name = HIVISION_MODNET_SESS.get_inputs()[0].name
output_name = HIVISION_MODNET_SESS.get_outputs()[0].name
im, width, length = read_modnet_image(input_image=input_image, ref_size=ref_size)
matte = HIVISION_MODNET_SESS.run([output_name], {input_name: im})
matte = (matte[0] * 255).astype("uint8")
matte = np.squeeze(matte)
mask = cv2.resize(matte, (width, length), interpolation=cv2.INTER_AREA)
b, g, r = cv2.split(np.uint8(input_image))
output_image = cv2.merge((b, g, r, mask))
return output_image
def get_modnet_matting_photographic_portrait_matting(
input_image, checkpoint_path, ref_size=512
):
global MODNET_PHOTOGRAPHIC_PORTRAIT_MATTING_SESS
if not os.path.exists(checkpoint_path):
print(f"Checkpoint file not found: {checkpoint_path}")
return None
if MODNET_PHOTOGRAPHIC_PORTRAIT_MATTING_SESS is None:
MODNET_PHOTOGRAPHIC_PORTRAIT_MATTING_SESS = load_onnx_model(
checkpoint_path, set_cpu=True
)
input_name = MODNET_PHOTOGRAPHIC_PORTRAIT_MATTING_SESS.get_inputs()[0].name
output_name = MODNET_PHOTOGRAPHIC_PORTRAIT_MATTING_SESS.get_outputs()[0].name
im, width, length = read_modnet_image(input_image=input_image, ref_size=ref_size)
matte = MODNET_PHOTOGRAPHIC_PORTRAIT_MATTING_SESS.run(
[output_name], {input_name: im}
)
matte = (matte[0] * 255).astype("uint8")
matte = np.squeeze(matte)
mask = cv2.resize(matte, (width, length), interpolation=cv2.INTER_AREA)
b, g, r = cv2.split(np.uint8(input_image))
output_image = cv2.merge((b, g, r, mask))
return output_image
def get_rmbg_matting(input_image: np.ndarray, checkpoint_path, ref_size=1024):
global RMBG_SESS
if not os.path.exists(checkpoint_path):
print(f"Checkpoint file not found: {checkpoint_path}")
return None
def resize_rmbg_image(image):
image = image.convert("RGB")
model_input_size = (ref_size, ref_size)
image = image.resize(model_input_size, Image.BILINEAR)
return image
if RMBG_SESS is None:
RMBG_SESS = load_onnx_model(checkpoint_path, set_cpu=True)
orig_image = Image.fromarray(input_image)
image = resize_rmbg_image(orig_image)
im_np = np.array(image).astype(np.float32)
im_np = im_np.transpose(2, 0, 1) # Change to CxHxW format
im_np = np.expand_dims(im_np, axis=0) # Add batch dimension
im_np = im_np / 255.0 # Normalize to [0, 1]
im_np = (im_np - 0.5) / 0.5 # Normalize to [-1, 1]
# Inference
result = RMBG_SESS.run(None, {RMBG_SESS.get_inputs()[0].name: im_np})[0]
# Post process
result = np.squeeze(result)
ma = np.max(result)
mi = np.min(result)
result = (result - mi) / (ma - mi) # Normalize to [0, 1]
# Convert to PIL image
im_array = (result * 255).astype(np.uint8)
pil_im = Image.fromarray(
im_array, mode="L"
) # Ensure mask is single channel (L mode)
# Resize the mask to match the original image size
pil_im = pil_im.resize(orig_image.size, Image.BILINEAR)
# Paste the mask on the original image
new_im = Image.new("RGBA", orig_image.size, (0, 0, 0, 0))
new_im.paste(orig_image, mask=pil_im)
return np.array(new_im)
def get_mnn_modnet_matting(input_image, checkpoint_path, ref_size=512):
if not os.path.exists(checkpoint_path):
print(f"Checkpoint file not found: {checkpoint_path}")
return None
try:
import MNN.expr as expr
import MNN.nn as nn
except ImportError as e:
raise ImportError(
"The MNN module is not installed or there was an import error. Please ensure that the MNN library is installed by using the command 'pip install mnn'."
) from e
config = {}
config["precision"] = "low" # 当硬件支持(armv8.2)时使用fp16推理
config["backend"] = 0 # CPU
config["numThread"] = 4 # 线程数
im, width, length = read_modnet_image(input_image, ref_size=512)
rt = nn.create_runtime_manager((config,))
net = nn.load_module_from_file(
checkpoint_path, ["input1"], ["output1"], runtime_manager=rt
)
input_var = expr.convert(im, expr.NCHW)
output_var = net.forward(input_var)
matte = expr.convert(output_var, expr.NCHW)
matte = matte.read() # var转换为np
matte = (matte * 255).astype("uint8")
matte = np.squeeze(matte)
mask = cv2.resize(matte, (width, length), interpolation=cv2.INTER_AREA)
b, g, r = cv2.split(np.uint8(input_image))
output_image = cv2.merge((b, g, r, mask))
return output_image
def get_birefnet_portrait_matting(input_image, checkpoint_path, ref_size=512):
global BIREFNET_V1_LITE_SESS
if not os.path.exists(checkpoint_path):
print(f"Checkpoint file not found: {checkpoint_path}")
return None
def transform_image(image):
image = image.resize((1024, 1024)) # Resize to 1024x1024
image = (
np.array(image, dtype=np.float32) / 255.0
) # Convert to numpy array and normalize to [0, 1]
image = (image - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225] # Normalize
image = np.transpose(image, (2, 0, 1)) # Change from (H, W, C) to (C, H, W)
image = np.expand_dims(image, axis=0) # Add batch dimension
return image.astype(np.float32) # Ensure the output is float32
orig_image = Image.fromarray(input_image)
input_images = transform_image(
orig_image
) # This will already have the correct shape
# 记录加载onnx模型的开始时间
load_start_time = time()
if BIREFNET_V1_LITE_SESS is None:
print("首次加载birefnet-v1-lite模型...")
if ONNX_DEVICE == "GPU":
print("onnxruntime-gpu已安装,尝试使用CUDA加载模型")
try:
import torch
except ImportError:
print(
"torch未安装,尝试直接使用onnxruntime-gpu加载模型,这需要配置好CUDA和cuDNN"
)
BIREFNET_V1_LITE_SESS = load_onnx_model(checkpoint_path)
else:
BIREFNET_V1_LITE_SESS = load_onnx_model(checkpoint_path, set_cpu=True)
# 记录加载onnx模型的结束时间
load_end_time = time()
# 打印加载onnx模型所花的时间
print(f"Loading ONNX model took {load_end_time - load_start_time:.4f} seconds")
input_name = BIREFNET_V1_LITE_SESS.get_inputs()[0].name
print(onnxruntime.get_device(), BIREFNET_V1_LITE_SESS.get_providers())
time_st = time()
pred_onnx = BIREFNET_V1_LITE_SESS.run(None, {input_name: input_images})[
-1
] # Use float32 input
pred_onnx = np.squeeze(pred_onnx) # Use numpy to squeeze
result = 1 / (1 + np.exp(-pred_onnx)) # Sigmoid function using numpy
print(f"Inference time: {time() - time_st:.4f} seconds")
# Convert to PIL image
im_array = (result * 255).astype(np.uint8)
pil_im = Image.fromarray(
im_array, mode="L"
) # Ensure mask is single channel (L mode)
# Resize the mask to match the original image size
pil_im = pil_im.resize(orig_image.size, Image.BILINEAR)
# Paste the mask on the original image
new_im = Image.new("RGBA", orig_image.size, (0, 0, 0, 0))
new_im.paste(orig_image, mask=pil_im)
return np.array(new_im)
|