【Matting】MODNet:实时人像抠图模型-onnx python部署

article/2025/9/28 4:51:32

上一篇博客【Matting】MODNet:实时人像抠图模型-笔记分析了MODNet的原理,本篇博客将使用python部署MODNet官方提供的onnx模型,其效果如下:

 在线人像抠图体验:CV案例

相关部署链接:

【Matting】MODNet:实时人像抠图模型-onnx C++部署

NCNN量化部署链接(模型大小仅为1/4):

【Matting】MODNet:实时人像抠图模型-NCNN C++量化部署

本文完整的代码:modnet onnx python部署

好了,废话不多说,正式开始。

一、下载onnx模型

首先,下载官方提供的onnx模型,官方的repo地址:https://github.com/ZHKKKe/MODNet.git,在onnx文件夹下有下载链接,这里就不给出来了。

二、部署

主要实现了图片抠图、摄像头抠图、视频抠图3个功能,代码如下(文章开头给出了可直接运行的带权重的压缩包):

PS:运行速度和电脑性能有关,可以修改代码使用GPU加速

import cv2
import time
from tqdm import tqdm
import numpy as np
import onnxruntime as rtclass Matting:def __init__(self, model_path='onnx_model\modnet.onnx', input_size=(512, 512)):self.model_path = model_pathself.sess = rt.InferenceSession(self.model_path)self.input_name = self.sess.get_inputs()[0].nameself.label_name = self.sess.get_outputs()[0].nameself.input_size = input_sizeself.txt_font = cv2.FONT_HERSHEY_PLAINdef normalize(self, im, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]):im = im.astype(np.float32, copy=False) / 255.0im -= meanim /= stdreturn imdef resize(self, im, target_size=608, interp=cv2.INTER_LINEAR):if isinstance(target_size, list) or isinstance(target_size, tuple):w = target_size[0]h = target_size[1]else:w = target_sizeh = target_sizeim = cv2.resize(im, (w, h), interpolation=interp)return imdef preprocess(self, image, target_size=(512, 512), interp=cv2.INTER_LINEAR):image = self.normalize(image)image = self.resize(image, target_size=target_size, interp=interp)image = np.transpose(image, [2, 0, 1])image = image[None, :, :, :]return imagedef predict_frame(self, bgr_image):assert len(bgr_image.shape) == 3, "Please input RGB image."raw_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)h, w, c = raw_image.shapeimage = self.preprocess(raw_image, target_size=self.input_size)pred = self.sess.run([self.label_name],{self.input_name: image.astype(np.float32)})[0]pred = pred[0, 0]matte_np = self.resize(pred, target_size=(w, h), interp=cv2.INTER_NEAREST)matte_np = np.expand_dims(matte_np, axis=-1)return matte_npdef predict_image(self, source_image_path, save_image_path):bgr_image = cv2.imread(source_image_path)assert len(bgr_image.shape) == 3, "Please input RGB image."matte_np = self.predict_frame(bgr_image)matting_frame = matte_np * bgr_image + (1 - matte_np) * np.full(bgr_image.shape, 255.0)matting_frame = matting_frame.astype('uint8')cv2.imwrite(save_image_path, matting_frame)def predict_camera(self):cap_video = cv2.VideoCapture(0)if not cap_video.isOpened():raise IOError("Error opening video stream or file.")beg = time.time()count = 0while cap_video.isOpened():ret, raw_frame = cap_video.read()if ret:count += 1matte_np = self.predict_frame(raw_frame)matting_frame = matte_np * raw_frame + (1 - matte_np) * np.full(raw_frame.shape, 255.0)matting_frame = matting_frame.astype('uint8')end = time.time()fps = round(count / (end - beg), 2)if count >= 50:count = 0beg = endcv2.putText(matting_frame, "fps: " + str(fps), (20, 20), self.txt_font, 2, (0, 0, 255), 1)cv2.imshow('Matting', matting_frame)if cv2.waitKey(1) & 0xFF == ord('q'):breakelse:breakcap_video.release()cv2.destroyWindow()def check_video(self, src_path, dst_path):cap1 = cv2.VideoCapture(src_path)fps1 = int(cap1.get(cv2.CAP_PROP_FPS))number_frames1 = cap1.get(cv2.CAP_PROP_FRAME_COUNT)cap2 = cv2.VideoCapture(dst_path)fps2 = int(cap2.get(cv2.CAP_PROP_FPS))number_frames2 = cap2.get(cv2.CAP_PROP_FRAME_COUNT)assert fps1 == fps2 and number_frames1 == number_frames2, "fps or number of frames not equal."def predict_video(self, video_path, save_path, threshold=2e-7):# 使用odf策略time_beg = time.time()pre_t2 = None  # 前2步mattepre_t1 = None  # 前1步mattecap = cv2.VideoCapture(video_path)fps = int(cap.get(cv2.CAP_PROP_FPS))size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))number_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)print("source video fps: {}, video resolution: {}, video frames: {}".format(fps, size, number_frames))videoWriter = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc('I', '4', '2', '0'), fps, size)ret, frame = cap.read()with tqdm(range(int(number_frames))) as t:for c in t:matte_np = self.predict_frame(frame)if pre_t2 is None:pre_t2 = matte_npelif pre_t1 is None:pre_t1 = matte_np# 第一帧写入matting_frame = pre_t2 * frame + (1 - pre_t2) * np.full(frame.shape, 255.0)videoWriter.write(matting_frame.astype('uint8'))else:# odferror_interval = np.mean(np.abs(pre_t2 - matte_np))error_neigh = np.mean(np.abs(pre_t1 - pre_t2))if error_interval < threshold < error_neigh:pre_t1 = pre_t2matting_frame = pre_t1 * frame + (1 - pre_t1) * np.full(frame.shape, 255.0)videoWriter.write(matting_frame.astype('uint8'))pre_t2 = pre_t1pre_t1 = matte_npret, frame = cap.read()# 最后一帧写入matting_frame = pre_t1 * frame + (1 - pre_t1) * np.full(frame.shape, 255.0)videoWriter.write(matting_frame.astype('uint8'))cap.release()print("video matting over, time consume: {}, fps: {}".format(time.time() - time_beg, number_frames / (time.time() - time_beg)))if __name__ == '__main__':model = Matting(model_path='onnx_model\modnet.onnx', input_size=(512, 512))# model.predict_camera()model.predict_image('images\\1.jpeg', 'output\\1.png')model.predict_image('images\\2.jpeg', 'output\\2.png')model.predict_image('images\\3.jpeg', 'output\\3.png')model.predict_image('images\\4.jpeg', 'output\\4.png')# model.predict_video("video\dance.avi", "output\dance_matting.avi")

三、效果


http://chatgpt.dhexx.cn/article/fibm7IW5.shtml

相关文章

【笔记】Robust High-Resolution Video Matting with Temporal Guidance

Robust High-Resolution Video Matting with Temporal Guidance算法笔记 一、算法简介二、网络结构三、训练1、数据集2、训练过程3、损失函数 Robust High-Resolution Video Matting with Temporal Guidance 论文地址 RobustVideoMatting 代码地址 Robust High-Resolution Vide…

【Matting】MODNet:实时人像抠图模型-笔记

paper&#xff1a;MODNet: Real-Time Trimap-Free Portrait Matting via Objective Decomposition (AAAI 2022) github&#xff1a;https://github.com/ZHKKKe/MODNet 抠图在线体验&#xff1a;CV案例 部署教程&#xff1a; 【Matting】MODNet&#xff1a;实时人像抠图模型…

Image Matting 客观评价指标、数据集及主观评价

Image Matting 客观评价指标、数据集及主观评价 2021.7更新 PPM-100数据集已经开放&#xff0c;GitHub&#xff0c;详情见下文章节2.4 目录 Image Matting 客观评价指标、数据集及主观评价2021.7更新 客观评价指标1. 精度1.1 SAD1.2 MSE 均方误差1.3 Gradient error1.4 Conne…

深度学习(7)之图像抠图 Image Matting算法调研

目录 1.Trimap和Strokes 2. 相关数据集 3.论文算法调研 3.1 Deep Image Matting 3.2 Semantic Image Matting 3.3 Background Matting 3.4 Background Matting V2 3.5 Semantic Human Matting 3.6 HAttMatting 3.7 MMNet&#xff1a;Towards Real-Time Automatic Portrait Matt…

【SHM】Semantic Human Matting抠图算法调试

前言&#xff1a; 2018年阿里的论文《Semantatic Human Matting》给出了抠图领域的一个新方法&#xff0c;可惜阿里并没有公布源码&#xff0c;而牛人在Github上对这个论文进行了复现&#xff0c;我也是依赖Github上的工程进行钻研&#xff0c;而在调试的过程中&#xff0c;发…

[Matting]论文阅读:Deep Image Matting 详细解读

[Matting]论文阅读&#xff1a;Deep Image Matting 详细解读 一 、摘要 任务二、方法2.1 第一部分&#xff08;Matting encoder-decoder stage&#xff09;2.2 第二部分&#xff08;Matting refinement stage&#xff09;2.3 数据部分&#xff08;Composed Datasets&#xff09…

【CVPR2022】MatteFormer: Transformer-Based Image Matting via Prior-Tokens

MatteFormer: Transformer-Based Image Matting via Prior-Tokens 中文题目: 借助先验Token的基于Transformer的图像抠图 paper&#xff1a;https://arxiv.org/pdf/2203.15662v1.pdf code&#xff1a;https://github.com/webtoon/matteformer 摘要 本文提出了一个基于Tran…

Image Matting代码和算法效果总结

本文参考了&#xff1a;http://blog.leanote.com/post/610167078qq.com/Image-Matting。作者给出了大部分matting-code的链接&#xff0c;说明也比较细致、系统&#xff0c;在这里向作者表示由衷地感谢&#xff01;以下是博客的原文&#xff1a; 肖总博客&#xff1a;http://3…

matting笔记_一周小结

去年刚入坑的旧笔记&#xff0c;刚翻出来… 1. 利用神经网络做抠图的入坑之作《Deep Image Matting》 详情见之前的笔记 matting系列论文笔记&#xff08;一&#xff09;&#xff1a;Deep Image Matting 由于image matting的工作没有特别好的综述&#xff0c;有的综述也不是…

Matting 基于DeepLearning 入门

前言 是比较清晰的用思维导图的形式介绍了一些Matting 基于DeepLearning 的经典论文&#xff0c;如 Deep Image matting可以通过这篇初步了解深度学习Matting领域该篇论文可以看作是基于深度学习研究Matting的开山之作&#xff0c;之后的许多有效、可行度高的做法都是基于这篇…

Matting和Segmentation区别及模型概述

一、两者区别 Segmentation&#xff1a;常被认为是硬分割&#xff08;Hard Segmentation&#xff09;&#xff0c;就是将图片中的像素分成多个类别&#xff0c;如果是前背景分割&#xff0c;那么就是分成两个类别&#xff0c;一个类别代表前景&#xff0c;一个类别代表背景。而…

如何清除Safari,Chrome和Firefox中的缓存,历史记录和Cookie

如何清除浏览器的cookie缓存&#xff1f;许多网站的通知,用户记住账号密码登录状态,都是通过浏览器cookie缓存,定期清理Safari&#xff0c;Chrome和Firefox中的缓存&#xff0c;历史记录和Cookie&#xff0c;可以让浏览器保持一个良好的状态&#xff0c;也可以保护我们的隐私。…

Nginx缓存服务

文章目录 一、缓存概述&#xff08;1&#xff09;缓存的作用&#xff08;2&#xff09;缓存常见的类型&#xff08;3&#xff09;Nginx缓存的原理 二、配置Nginx缓存&#xff08;1&#xff09;主配置文件中缓存的语法&#xff08;2&#xff09;配置Nginx缓存-实验环境-实验目的…

android7.0清除缓存,iPhone7如何清理应用缓存 iphone7清理应用缓存教程

手机使用后会留下一些缓存垃圾&#xff0c;那么 iPhone7如何清理应用缓存&#xff1f; 下面就带来iphone7清理应用缓存教程&#xff0c;一起来学习下。 方法1&#xff1a;强行重启 强行重启(也叫冷重启)能够帮助iOS的设备清理一下临时文件&#xff0c;定期强行重启一下设备&…

Chrome Edge Firefox Safari 如何清除 DNS 缓存

Chrome Edge Firefox Safari 如何清除 DNS 缓存 如何清除浏览器的 DNS 缓存 (Chrome, Firefox, Safari) Chrome Chromium Edge Firefox Safari clear DNS Cache, flush DNS cache 请访问原文链接&#xff1a;https://sysin.org/blog/clear-browser-dns-cache/&#xff0c;查…

苹果电脑怎么清理垃圾和缓存文件,mac如何清理系统缓存文件

电脑使用的时间越久&#xff0c;系统运行就会变得越来越卡&#xff0c;这是Windows和Mac系统都会出现的现象。为了提高系统运行速度&#xff0c;我们有必要清理一下电脑缓存。那么苹果电脑怎么清理垃圾和缓存文件&#xff1f;本指南将详细讲解清理Mac缓存的技巧&#xff0c;还补…

浏览器缓存导致的问题:

1、需要的效果如下&#xff1a; 2、添加样式之后&#xff0c;样式会生效&#xff0c;但是没有达到上面的效果&#xff0c;表单会消失掉&#xff0c;只剩下一个黑色的背景图 4、原因&#xff1a; 因为浏览器的缓存问题导致的样式没有显示出来 5、解决办法&#xff1a; 清除掉…

浏览器缓存

文章目录 前端缓存|后端缓存按缓存位置分类缓存过程memory cachedisk cacheService WorkerPush Cache 强制缓存适用场景ExpiresCache-Control 协商缓存&#xff08;也叫对比缓存&#xff09;适用场景ETag和Last-Modified区别 缓存相关问题缓存穿透缓存击穿缓存雪崩 前端缓存|后…

苹果清除缓存_苹果手机卡顿别着急换,调整这5个功能,iPhone 6S还可以再战两年...

阅读本文前&#xff0c;请您先点击上面的“议科技”&#xff0c;关注&#xff0c;这样您就可以继续收到最新文章了。每天都有分享。完全是免费订阅&#xff0c;请放心关注。 平时在使用苹果手机的时候&#xff0c;时间用久了&#xff0c;是不是觉得手机有些卡顿&#xff1f;使用…

如何在Mac iPhone和iPad上清除Safari缓存?

每当您在Safari中浏览网络时&#xff0c;浏览器都会存储网站数据&#xff0c;因此您不必在每次重新访问网站时都再次下载该数据。从理论上讲&#xff0c;这应该可以加快您的浏览体验&#xff0c;但是在某些情况下&#xff0c;您可能需要清除缓存并重新开始。如何清除Safari缓存…