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

注意本文后面的话,百度这个技术效果太差劲了,国外这 https://www.remove.bg/ 个比百度强大很多。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using Newtonsoft.Json;
using System.Web;
using Newtonsoft.Json.Linq;
using System.ComponentModel; namespace IDPhoto
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainWindow_Loaded);
worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); } string strImageBase64 = "";
BackgroundWorker worker;
object lockObj = new object();
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{ btnDoWork.IsEnabled = true;
btnDoWork.Visibility = System.Windows.Visibility.Collapsed;
loading.Visibility = Visibility.Collapsed;
} void worker_DoWork(object sender, DoWorkEventArgs e)
{ if (Common.token == "")
{
Common.token = getAccessToken();
Config.SaveConfig();
} string sPost = "image=" + HttpUtility.UrlEncode(strImageBase64, Encoding.UTF8) + "&type=foreground";
string sResult = HttpHelper.httpPost("https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg?access_token=" + Common.token, sPost);
/*
{"log_id": 3992278826748564717, "foreground": "iVBORw0KGgoAAAANSUhEUgAAA0gAAAIMCAYAAADPWYwVAA
*/
JToken jt = JToken.Parse(sResult);
string sBase64 = "" + jt["foreground"];
Dispatcher.Invoke(new Action(() =>
{
if (sBase64 != "")
{
parseImageFromBase64(sBase64);
}
else
{ MessageBox.Show(sResult);
} })); } void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Config.loadConfig();//主要是加载保存的token,以免多少调用,token能有1个月左右的游戏时间 } //拖放文件支持的方法:TextBox_PreviewDragOver和TextBox_PreviewDrop private void TextBox_PreviewDragOver(object sender, DragEventArgs e)
{ e.Effects = DragDropEffects.Copy;
e.Handled = true;
} private void TextBox_PreviewDrop(object sender, DragEventArgs e)
{ if (worker.IsBusy) return;
string sSelectFile = "";
foreach (string f in (string[])e.Data.GetData(DataFormats.FileDrop))
{ if (f.ToLower().EndsWith(".png") || f.ToLower().EndsWith(".jpg") || f.ToLower().EndsWith(".bmp"))
{
Title = sSelectFile=f;
} }
if (sSelectFile == "")
{
return;
}
else { ProcessImage(sSelectFile); } } private void ProcessImage(string sFile) { loading.Visibility = Visibility.Visible;
byte[] buffer= File.ReadAllBytes(sFile);
strImageBase64 = Convert.ToBase64String(buffer);//Properties.Resources.testImgData;
btnDoWork.IsEnabled = false;
worker.RunWorkerAsync(); } private void btnDoWork_Click(object sender, RoutedEventArgs e)
{ if (worker.IsBusy) return;
System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog ();
dlg.Filter = "图片文件|*.jpg;*.png;*.bmp";
if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return;
} ProcessImage(dlg.FileName); } ///Base64 string 转 BitmapImage
void 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();
image1.Source = null;
image1.Source = bmp; } ///获取TOKEN ,参数client_id和client_secret在百度自己的后台APP的key和secret
string getAccessToken()
{ string s = HttpHelper.httpPost("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=xxxxxxx&client_secret=xxxxxxxxxx", ""); BaiduTokenData d = JsonConvert.DeserializeObject<BaiduTokenData>(s);
if (d != null)
{ return d.access_token;
} return ""; }
void testDemo()
{ string s = Uri.UnescapeDataString("data:image/jpeg;base64," + Properties.Resources.testImgData); string s2 = HttpHelper.httpPost("http://ai.baidu.com/aidemo", "image=" + s + "&image_url=&type=body_seg");
Title = s2; } } public class BaiduTokenData
{
/// <summary>
///
/// </summary>
public string refresh_token { get; set; }
/// <summary>
///
/// </summary>
public int expires_in { get; set; }
/// <summary>
///
/// </summary>
public string session_key { get; set; }
/// <summary>
///
/// </summary>
public string access_token { get; set; }
/// <summary>
/// brain_body_seg public brain_all_scope vis-faceverify_faceverify_h5-face-liveness brain_body_analysis brain_body_attr vis-faceverify_FACE_V3 brain_gesture_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi
/// </summary>
public string scope { get; set; }
/// <summary>
///
/// </summary>
public string session_secret { get; set; }
} } ---------------------------------------------------
以下是HttpHelper 类代码:
---------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Windows; namespace IDPhoto
{
public class HttpHelper
{ public static CookieContainer myCookieContainer = new CookieContainer();
private static string myReferer = "http://ai.baidu.com/tech/body/seg";
public static bool checkLogin()
{ string s = "";
bool loginOK = false;
try
{
loginOK = s.Contains("sso_login_status=1");
if (loginOK)
{
Common.cookie = s;
setCookieContainer(s, new Uri("http://love.163.com/home?ydMobilePassport=false&ydMobile=0", UriKind.Absolute));
}
// MessageBox.Show(s);
}
catch (Exception ex)
{
MessageBox.Show("" + ex.Message);
return false;
} return loginOK;
} public static void setCookieContainer (string cookie ,Uri url)
{ string[] arrCookie = cookie.Split(';');
myCookieContainer = new CookieContainer(); //加载Cookie
foreach (string sCookie in arrCookie)
{
myCookieContainer.SetCookies(url, sCookie);
} } public static string httpGet(string sUrl)
{ string s = "";
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("" + sUrl);
req.CookieContainer = myCookieContainer;
req.Referer = myReferer;
// req.TransferEncoding = "UTF8";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
myCookieContainer.Add(resp.Cookies);
StreamReader r = new StreamReader(resp.GetResponseStream());
s = r.ReadToEnd();
r.Close();
resp.Close();
}
catch (Exception ex)
{ s = ex.Message; }
return s; } public static string httpPost(string sUrl,string para)
{ string s = "";
try
{
byte[] data = Encoding.ASCII.GetBytes(para);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("" + sUrl);
req.CookieContainer = myCookieContainer;
// req.Headers.Add("Cookie",Properties.Resources.cookie);
req.Referer = myReferer;
req.ContentType = "application/x-www-form-urlencoded";
// req.TransferEncoding = "UTF8";
req.Method = "POST";
if (para != "")
{
req.ContentLength = data.Length;
req.GetRequestStream().Write(data, 0, data.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
myCookieContainer.Add(resp.Cookies);
StreamReader r = new StreamReader(resp.GetResponseStream());
s = r.ReadToEnd();
r.Close();
resp.Close();
}
catch (Exception ex)
{ s = ex.Message; }
return s; } } public class Common { public static string cookie { get; set; } public static string token { get; set; }
} }

  

UI 代码:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:IDPhoto" x:Class="IDPhoto.MainWindow"
Title="MainWindow" Height="1301" Width="1126">
<Grid x:Name="gridMain" AllowDrop="True" Background="Gray" IsHitTestVisible="True"
PreviewDragOver="TextBox_PreviewDragOver" PreviewDrop="TextBox_PreviewDrop"> <Button Content="btnStart" Height="41" HorizontalAlignment="Left" Margin="25,27,0,0" x:Name="btnDoWork" VerticalAlignment="Top" Width="250" Click="btnDoWork_Click" />
<Border Background="#FF1133A6" BorderBrush="WhiteSmoke" BorderThickness="5" Width="432" Height="502" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="25,101,0,0" >
<Image x:Name="image1" Stretch="Fill" />
</Border>
<local:Loading x:Name="loading" Visibility="Collapsed" HorizontalAlignment="Left" Height="100" Margin="366,219,0,0" VerticalAlignment="Top" Width="100"/>
</Grid>
</Window>

  

后面的话:本来打算做个APP或Windows应用什么的,可惜后面对比了国外这个 https://www.remove.bg/ 后感觉百度的差距太大了。就无语了。

c# 利用百度图像处理【人像分割】一键抠图的更多相关文章

  1. 利用百度API Store接口进行火车票查询

    火车票查询 项目源码下载链接: Github:https://github.com/VincentWYJ/TrainTicketQuery 博客文件:http://files.cnblogs.com/ ...

  2. 利用百度语音API进行语音识别。

    由于项目需要,这几天都在试图利用百度语音API进行语音识别.但是识别到的都是“啊,哦”什么的,我就哭了. 这里我只是分享一下这个过程,错误感觉出现在Post语音数据那一块,可能是转换问题吧. API请 ...

  3. 利用百度词典API和Volley网络库开发的android词典应用

     关于百度词典API的说明,地址在这里:百度词典API介绍 关于android网络库Volley的介绍说明,地址在这里:Android网络通信库Volley 首先我们看下大体的界面布局!

  4. 利用百度地图API,获取经纬度坐标

    利用百度地图API,获取经纬度坐标 代码很简单,但在网上没找到现成的获取地图经纬度的页面. 就是想,给当前页面传递一个经纬度,自动定位到此经纬度.然后可以重新选择,选择完返回经纬度. 效果如下: 源代 ...

  5. 【百度地图API】建立全国银行位置查询系统(四)——如何利用百度地图的数据生成自己的标注

    原文:[百度地图API]建立全国银行位置查询系统(四)--如何利用百度地图的数据生成自己的标注 摘要: 上一章留个悬念,"如果自己没有地理坐标的数据库,应该怎样制作银行的分布地图呢?&quo ...

  6. 利用百度地图API和群蚁算法,对TSP问题进行模拟与求解

    前言 最近由于换了工作,期间也有反思和总结上家公司的得失,总觉得有什么事情当初可以完成或者完成得更好,其中TSP问题就是其中之一.当初在开发一个仓配系统的时候,有一个线路排程的需求,当时自己简单在纸上 ...

  7. 利用百度接口进行人脸识别并保存人脸jpg文件

    利用百度接口进行人脸识别,根据返回的人脸location用opencv切割保存. # coding : UTF-8 from aip import AipFace import cv2 import ...

  8. SEO如何利用百度知道日引流上千IP

    个人小站长.SEO们经常为网站没有流量而发愁,一个没有流量的网站就像一个不喝水的人,迟早得死.没有流量,就没有PV,也就是说你的网站只是 给你一个人看的,那做站有什么意义呢?网站上所发布的内容都是分享 ...

  9. 利用百度翻译API,获取翻译结果

    利用百度翻译API,获取翻译结果 translate.py #!/usr/bin/python #-*- coding:utf-8 -*- import sys reload(sys) sys.set ...

随机推荐

  1. codeforces 2A Winner (好好学习英语)

    Winner 题目链接:http://codeforces.com/contest/2/problem/A ——每天在线,欢迎留言谈论. 题目大意: 最后结果的最高分 maxscore.在最后分数都为 ...

  2. Spark应用【根据新df更新旧df】

    // 主键字段保持不变,再转换回来 var columnMap:Map[String, String] = Map() for(key <- keysOpt){ columnMap += (ke ...

  3. Oracle的实例恢复解析

    在数据库服务器异常断电重启后,数据库会进行实例恢复,那么实例恢复的过程中Oracle做了什么操作呢?参考官网在这里做一下解释,菜鸟水平有限,欢迎勘正. 首先说下实例恢复的定义: Instance re ...

  4. 转:Log Explorer使用说明恢复被误删除的数据

    一.介绍 Log Explorer主要用于对MSSQLServer的事物分析和数据恢复.你可以浏览日志.导出数据.恢复被修改或者删除的数据(包括执行过update,delete,drop和trunca ...

  5. 15个实用的PHP正则表达式

    对于开发人员来说,正则表达式是一个非常有用的功能,它提供了 查找,匹配,替换 句子,单词,或者其他格式的字符串.这篇文章主要介绍了15个超实用的php正则表达式,需要的朋友可以参考下.在这篇文章里,我 ...

  6. C# -- 使用Aspose.Cells创建和读取Excel文件

    使用Aspose.Cells创建和读取Excel文件 1. 创建Excel Aspose.Cells.License li = new Aspose.Cells.License(); li.SetLi ...

  7. Python里面search()和match()的区别

    转自https://www.cnblogs.com/aaronthon/p/9435967.html match()函数只检测字符串开头位置是否匹配,匹配成功才会返回结果,否则返回None searc ...

  8. 【Linux基础】Linux下软件包管理(rpm-deb-yast-yum)

    软件包管理是指系统中一种安装和维护软件的方法.通常软件以包的形式存储在仓库(repository)中,能满足许多人所有需要的软件. 在GNU/Linux(以下简称Linux)操作系统中,RPM和DPK ...

  9. sboot mybatis

    https://www.cnblogs.com/lspz/p/6723603.html spring.datasource.url=jdbc:mysql://10.46.52.205:3306/tes ...

  10. Python 进程管理工具 Supervisor 使用教程

    Supervisor 是基于 Python 的进程管理工具,只能运行在 Unix-Like 的系统上,也就是无法运行在 Windows 上.Supervisor 官方版目前只能运行在 Python 2 ...