C# PaddleInference.PP-HumanSeg 人像分割 替换背景色

效果

项目

VS2022+.net4.8+OpenCvSharp4+Sdcb.PaddleInference

包含4个分割模型

modnet-hrnet_w18

modnet-mobilenetv2

ppmatting-hrnet_w18-human_512

ppmattingv2-stdc1-human_512

代码

复制代码
using OpenCvSharp;
using Sdcb.PaddleInference;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using YamlDotNet.RepresentationModel;
 
namespace PaddleInference.PP_HumanSeg_人像分割_替换背景色
{
    public class PaddleSeger : IDisposable
    {
        private readonly PaddlePredictor _p;
        public PaddleSeger(PaddleConfig config, string deployYamlPath)
            : this(config.CreatePredictor(), deployYamlPath)
        {
        }
        public PaddleSeger(PaddlePredictor predictor, string deployYamlPath)
        {
            _p = predictor;
            var yaml = new YamlStream();
            using (FileStream ymlFile = File.OpenRead(deployYamlPath))
                yaml.Load(new StreamReader(ymlFile));
            YamlDocument doc = yaml.Documents[0];
        }
        public PaddleSeger(string modelDir) : this(PaddleConfig.FromModelFiles(
            Path.Combine(modelDir, "model.pdmodel"),
            Path.Combine(modelDir, "model.pdiparams")).Apply(PaddleDevice.Mkldnn()),
            Path.Combine(modelDir, "deploy.yaml"))
        {
        }
        public Mat Run(Mat src)
        {
            Mat dest;
            using (PaddleTensor input = _p.GetInputTensor(_p.InputNames[0]))
            {
                Mat bgr = src.CvtColor(ColorConversionCodes.BGR2RGB);
                Mat normalized = Normalize(bgr);
                float[] data = ExtractMat(normalized);
                normalized.Dispose();
                bgr.Dispose();
                input.Shape = new int[] { 1, 3, src.Rows, src.Cols };
                input.SetData(data);
            }
            if (!_p.Run())
            {
                throw new Exception("PaddlePredictor(Seger) run failed.");
            }
            using (PaddleTensor output = _p.GetOutputTensor(_p.OutputNames[0]))
            {
                float[] rawData = output.GetData<float>();
                byte[] data = Array.ConvertAll(rawData, d => (byte)(d * 255));
                GCHandle gc = GCHandle.Alloc(data, GCHandleType.Pinned);
                dest = new Mat(output.Shape[2], output.Shape[3], MatType.CV_8UC1, gc.AddrOfPinnedObject());
                gc.Free();
            }
            return dest;
        }
        private static Mat Normalize(Mat src)
        {
            Mat normalized = new Mat();
            src.ConvertTo(normalized, MatType.CV_32FC3, 1.0 / 255);
            Mat[] bgr = normalized.Split();
            float[] scales = new[] { 2.0f, 2.0f, 2.0f };
            float[] means = new[] { 0.5f, 0.5f, 0.5f };
            for (int i = 0; i < bgr.Length; ++i)
            {
                bgr[i].ConvertTo(bgr[i], MatType.CV_32FC1, 1.0 * scales[i], (0.0 - means[i]) * scales[i]);
            }
            normalized.Dispose();
            Mat dest = new Mat();
            Cv2.Merge(bgr, dest);
            foreach (Mat channel in bgr)
            {
                channel.Dispose();
            }
            return dest;
        }
        internal static float[] ExtractMat(Mat src)
        {
            int rows = src.Rows;
            int cols = src.Cols;
            float[] result = new float[rows * cols * 3];
            GCHandle resultHandle = default;
            try
            {
                resultHandle = GCHandle.Alloc(result, GCHandleType.Pinned);
                IntPtr resultPtr = resultHandle.AddrOfPinnedObject();
                for (int i = 0; i < src.Channels(); ++i)
                {
                    Mat dest = new Mat(rows, cols, MatType.CV_32FC1, resultPtr + i * rows * cols * sizeof(float));
                    Cv2.ExtractChannel(src, dest, i);
                    dest.Dispose();
                }
            }
            finally
            {
                resultHandle.Free();
            }
            return result;
        }
        public void Dispose()
        {
            _p.Dispose();
        }
    }
}

下载

源码下载

相关推荐
IvanCodes13 小时前
RAG 实战教程(一):RAG 工作原理与完整流程——分片、索引、召回、重排和生成
人工智能·后端·agent
今天AI了吗14 小时前
合规场景下的 AI 推理可解释性:Attention 可视化与推理路径追踪的工程实践
人工智能
周末程序猿14 小时前
浅析大模型推理十二篇之KV Cache
人工智能
鱼樱前端14 小时前
用 AI 做内容变收入
前端·人工智能·ai编程
Dawson Zhu15 小时前
基于Palantir Foundry构建半导体制造AI友好型数据中台:从良率分析场景谈起
人工智能·语言模型·架构·制造·agi
fthux15 小时前
装闭 RenoPit 源码解析(04):装修图纸和合同文件上传处理流程
人工智能·ai·开源·github·open source·renopit
hez201016 小时前
.NET 11 Runtime Async 详解
c#·.net·.net core
weixin_4462608516 小时前
从被动镜像到主动智能体:面向网络物理人工智能的整体论数字孪生(HDT-Net)
网络·人工智能
秋枫要学习16 小时前
你的鼠标,正在被 AI 抢走
人工智能·计算机外设