zoukankan      html  css  js  c++  java
  • CSharp: Image Matting

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Windows.Media.Imaging; //PresentationCore  //WindowsBase
    using System.Windows.Media;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System.Net;
    using System.IO;
    using System.Net.Http;
    using System.Text;
    
    public partial class Default2 : System.Web.UI.Page
    {
    
        /// <summary>
        /// 2020-12-26 涂聚文(Geovin Du)
        /// 人像抠图 百度AI的API
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            //
            string sToken = AccessToken.getAccessToken();
            JToken st = JToken.Parse(sToken);
            JObject jsonst = JObject.Parse(sToken);
            BaiduAITokenData we = JsonConvert.DeserializeObject<BaiduAITokenData>(sToken);
            //Response.Write(we.access_token+"<br/><br/>");
            //
            string sResult = body_seg();
            JToken jt = JToken.Parse(sResult);
            JObject jsonimg = JObject.Parse(sResult);
    
    
            BaiduAIBody body = JsonConvert.DeserializeObject<BaiduAIBody>(sResult);
            // Bitmap bmp = GetImageFromBase64(body.foreground);
            this.Image1.ImageUrl = "data:image/png;base64," + body.foreground;  //data:image/jpeg;base64,
    
            this.Image2.ImageUrl = "data:image/png;base64," + body.scoremap;
            //BitmapImage bmp = parseImageFromBase64(body.foreground);
            
    
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public String getFileBase64(String fileName)
        {
            FileStream filestream = new FileStream(fileName, FileMode.Open);
            byte[] arr = new byte[filestream.Length];
            filestream.Read(arr, 0, (int)filestream.Length);
            string baser64 = Convert.ToBase64String(arr);
            filestream.Close();
            return baser64;
        }
        /// <summary>
        /// 人像图获取
        /// </summary>
        /// <returns></returns>
        public string body_seg()
        {
            string token = AccessToken.TOKEN;// AccessToken.getAccessToken();// "[调用鉴权接口获取的token]";
            string sToken = AccessToken.getAccessToken();
            JToken st = JToken.Parse(sToken);
            JObject jsonst = JObject.Parse(sToken);
            BaiduAITokenData we = JsonConvert.DeserializeObject<BaiduAITokenData>(sToken);
            //Response.Write(token + "<br/>");
            string host = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg?access_token=" + we.access_token;
            Encoding encoding = Encoding.ASCII;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.ContentType = "application/x-www-form-urlencoded";
            request.KeepAlive = true;
            string file = Server.MapPath("Images/涂聚文1.jpg");
            // 图片的base64编码
            string base64 = getFileBase64(file);
            String str = "image=" + HttpUtility.UrlEncode(base64);//
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
            string result = reader.ReadToEnd();
            Console.WriteLine("人像分割:");
            Console.WriteLine(result);
            //Response.Write(result);
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sBase64"></param>
        /// <returns></returns>
        BitmapImage parseImageFromBase64(string sBase64)
        {
    
            char[] c = sBase64.ToCharArray();// Properties.Resources.testImgData .ToCharArray();
            byte[] buffer = System.Convert.FromBase64CharArray(c, 0, c.Length);
            MemoryStream m = new MemoryStream(buffer);
            m.Position = 0;
            BitmapImage bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.StreamSource = m;
            bmp.EndInit();       
            return bmp;
        }
    
    }
    

      百度AI开放平台-人像分割: http://ai.baidu.com/tech/body/seg

     

     https://github.com/emgucv/emgucv  C#

    https://github.com/opencv/opencv_extra C++

    https://github.com/opencv/opencv

    https://pypi.tuna.tsinghua.edu.cn/simple/opencv-python/  Python

        /// <summary>
        /// 图像文件转Base64 Geovin Du
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public string ImageToBase64(string filepath)
        {
            string base64String = string.Empty;
            try
            { 
                   // string path = "D:\SampleImage.jpg";
                    using (System.Drawing.Image image = System.Drawing.Image.FromFile(filepath))
                    {
                        using (MemoryStream m = new MemoryStream())
                        {
                            image.Save(m, image.RawFormat);
                            byte[] imageBytes = m.ToArray();
                            base64String = Convert.ToBase64String(imageBytes);
                            return base64String;
                        }
                    }
            }
            catch(Exception ex)
            {
                ex.Message.ToString();
            }
            return base64String;
        }
        /// <summary>
        /// Base64转image
        /// </summary>
        /// <param name="base64String"></param>
        /// <returns></returns>
        public System.Drawing.Image Base64ToImage(string base64String)
        {
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
            ms.Write(imageBytes, 0, imageBytes.Length);
            System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
            return image;
        }
    

     Background Removal API  https://www.remove.bg/zh/g/developers

    https://github.com/brilam/remove-bg  python

    https://github.com/mtownsend5512/remove-bg php

    https://github.com/remove-bg/go  go

    https://github.com/remove-bg

                      //https://www.remove.bg/zh/api
                       HttpClient client = new HttpClient();
                     // using (client = new HttpClient());
                        //
                        using (var formData = new MultipartFormDataContent())
                        {
                            formData.Headers.Add("X-Api-Key", "geovindu 涂聚文 Geovin Du");
                            formData.Add(new ByteArrayContent(File.ReadAllBytes(Server.MapPath("Images/pdf.jpg"))), "image_file", Server.MapPath("Images/2.jpg"));
                            formData.Add(new StringContent("auto"), "size");////preview,full,auto,regular
                            var response = client.PostAsync("https://api.remove.bg/v1.0/removebg", formData).Result;
    
                            if(response.IsSuccessStatusCode) {
                                FileStream fileStream = new FileStream(Server.MapPath("Images/geovindu_no-bg.png"), FileMode.Create, FileAccess.Write, FileShare.None);
                                response.Content.CopyToAsync(fileStream).ContinueWith((copyTask) =>{ fileStream.Close(); });
                            } else {
                                Console.WriteLine("Error: " + response.Content.ReadAsStringAsync().Result);
                            }
                        }
    

      

     

            /// <summary>
            /// 改换背景色
            /// 把人像填色>150,<150 把背景色填写了
            /// </summary>
            /// <param name="scrBitmap"></param>
            /// <param name="newColor">改为新的背景色</param>
            /// <returns></returns>
            public static Bitmap ChangeColor(Bitmap scrBitmap,Color newColor)
            {
    
                //https://stackoverflow.com/questions/17208254/how-to-change-pixel-color-of-an-image-in-c-net
                //You can change your new color here. Red,Green,LawnGreen any..
               // Image imggree = Image.FromFile("green1.jpg");
               // Bitmap grebt = new Bitmap(imggree);
               //得到背景色(从坐标1,1得到)
               // Color greenColor = grebt.GetPixel(1, 1);
                //Color newColor = greenColor;// Color.Green;
                Color actualColor;
                //actualColor = scrBitmap.GetPixel(1, 1);
                //make an empty bitmap the same size as scrBitmap
                Bitmap newBitmap = new Bitmap(scrBitmap.Width, scrBitmap.Height);
    
                for (int i = 0; i < scrBitmap.Width; i++)
                {
                    for (int j = 0; j < scrBitmap.Height; j++)
                    {
                        //get the pixel from the scrBitmap image
                       actualColor = scrBitmap.GetPixel(i, j);
    
                        // > 150 because.. Images edges can be of low pixel colr. if we set all pixel color to new then there will be no smoothness left.
                        if (actualColor.A < 150)  //>150 人像改了颜色
                            newBitmap.SetPixel(i, j, newColor);
                        else
                            newBitmap.SetPixel(i, j, actualColor);
                    }
    
                }
    
                return newBitmap;
            }
    

      

     

  • 相关阅读:
    20135213 20135231 信息安全系统设计基础课程第二次实验报告
    20135213——信息安全系统设计基础第十二周学习总结
    20135213——信息安全系统设计基础第十一周学习总结
    20135220谈愈敏Blog5_系统调用(下)
    20135220谈愈敏Linux Book_5
    20135220谈愈敏Blog4_系统调用(上)
    20135220谈愈敏Linux Book_1&2
    20135220谈愈敏Blog3_构造一个简单的Linux系统MenuOS
    20135220谈愈敏Blog2_操作系统是如何工作的
    20135220谈愈敏Blog1_计算机是如何工作的
  • 原文地址:https://www.cnblogs.com/geovindu/p/14191320.html
Copyright © 2011-2022 走看看