【使用攻略】【图像技术】拉伸图像恢复
一、功能描述
当我们看电影的时候,有时候如果电影的比例不对,会发现电影看的相当别扭。同理,当我们看一张图片时,如果感到这张图片让人看起来很别扭,那就有可能是这张图片的长宽比例不对,这时候就可以采取百度拉伸图片恢复技术,将图像内容恢复成正常比例。
二、使用攻略
说明:本文采用C# 语言,开发环境为.Net Core 2.1,采用在线API接口方式实现。
(1)平台接入
登陆 百度智能云-管理中心 创建 “图像处理”应用,获取 “API Key ”和 “Secret Key” :https://console.bce.baidu.com/ai/?_=1564037948120#/ai/imageprocess/overview/index
(2)接口文档
文档地址:https://ai.baidu.com/docs#/ImageProcessing-API/f83bad8b
接口描述:自动识别过度拉伸的图像,将图像内容恢复成正常比例。
请求说明
返回说明
(3)源码共享
3.1-根据 API Key 和 Secret Key 获取 AccessToken
///
/// 获取百度access_token
///
/// API Key
/// Secret Key
///
public static string GetAccessToken(string clientId, string clientSecret)
{
string authHost = "https://aip.baidubce.com/oauth/2.0/token";
HttpClient client = new HttpClient();
List> paraList = new List>();
paraList.Add(new KeyValuePair("grant_type", "client_credentials"));
paraList.Add(new KeyValuePair("client_id", clientId));
paraList.Add(new KeyValuePair("client_secret", clientSecret));
HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
string result = response.Content.ReadAsStringAsync().Result;
JObject jo = (JObject)JsonConvert.DeserializeObject(result);
string token = jo["access_token"].ToString();
return token;
}
3.2-调用API接口获取识别结果
1、在Startup.cs 文件 的 Configure(IApplicationBuilder app, IHostingEnvironment env) 方法中开启虚拟目录映射功能:
string webRootPath = HostingEnvironment.WebRootPath;//wwwroot目录
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(webRootPath, "Uploads", "BaiduAIs")),
RequestPath = "/BaiduAIs"
});
2、 建立Index.cshtml文件
2.1 前台代码: 由于html代码无法原生显示,只能简单说明一下:
主要是一个form表单,需要设置属性enctype="multipart/form-data",否则无法上传图片;
form表单里面有四个控件:
一个Input:type="file",asp-for="FileUpload" ,上传图片用;
一个Input:type="submit",asp-page-handler="StretchRestore" ,提交并返回识别结果。
一个img:src="@Model.curPath",显示需要识别的图片。
一个img:src="@Model.imgProcessPath",显示车辆分割后的前景抠图。
最后显示后台 msg 字符串列表信息,如果需要输出原始Html代码,则需要使用@Html.Raw()函数。
2.2 后台代码:
[BindProperty]
public IFormFile FileUpload { get; set; }
[BindProperty]
public string ImageUrl { get; set; }
private readonly IHostingEnvironment HostingEnvironment;
public List msg = new List();
public string curPath { get; set; }
public string imgProcessPath { get; set; }
public ImageProcessModel(IHostingEnvironment hostingEnvironment)
{
HostingEnvironment = hostingEnvironment;
}
public async Task OnPostStretchRestoreAsync()
{
if (FileUpload is null)
{
ModelState.AddModelError(string.Empty, "本地图片!");
}
if (!ModelState.IsValid)
{
return Page();
}
msg = new List();
string webRootPath = HostingEnvironment.WebRootPath;//wwwroot目录
string fileDir = Path.Combine(webRootPath, "Uploads//BaiduAIs//");
string imgName = await UploadFile(FileUpload, fileDir);
string fileName = Path.Combine(fileDir, imgName);
string imgBase64 = Common.GetFileBase64(fileName);
curPath = Path.Combine("/BaiduAIs/", imgName);//需在Startup.cs 文件 的 Configure(IApplicationBuilder app, IHostingEnvironment env)方法中开启虚拟目录映射功能
string result = GetImageJson(imgBase64, “你的API KEY”, “你的SECRET KEY”);
JObject jo = (JObject)JsonConvert.DeserializeObject(result);
try
{
string imageProcessBase64 = jo["image"].ToString();
msg.Add("拉伸图像恢复");
msg.Add("log_id:" + jo["log_id"].ToString());
string processImgName = Guid.NewGuid().ToString("N") + ".png";
string imgSavedPath = Path.Combine(webRootPath, "Uploads//BaiduAIs//", processImgName);
imgProcessPath = Path.Combine("BaiduAIs//", processImgName);
await GetFileFromBase64(imageProcessBase64, imgSavedPath);
}
catch (Exception e)
{
msg.Add(result);
}
return Page();
}
///
/// 上传文件,返回文件名
///
/// 文件上传控件
/// 文件绝对路径
///
public static async Task UploadFile(IFormFile formFile, string fileDir)
{
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
string extension = Path.GetExtension(formFile.FileName);
string imgName = Guid.NewGuid().ToString("N") + extension;
var filePath = Path.Combine(fileDir, imgName);
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
await formFile.CopyToAsync(fileStream);
}
return imgName;
}
///
/// 返回图片的base64编码
///
/// 文件绝对路径名称
///
public static 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;
}
///
/// 文件base64解码
///
/// 文件base64编码
/// 生成文件路径
public static async Task GetFileFromBase64(string base64Str, string outPath)
{
var contents = Convert.FromBase64String(base64Str);
using (var fs = new FileStream(outPath, FileMode.Create, FileAccess.Write))
{
fs.Write(contents, 0, contents.Length);
fs.Flush();
}
}
///
/// 图像识别Json字符串
///
/// 图片base64编码
/// API Key
/// Secret Key
///
public static string GetImageJson(string strbaser64, string clientId, string clientSecret)
{
string token = GetAccessToken(clientId, clientSecret);
string host = "https://aip.baidubce.com/rest/2.0/image-process/v1/stretch_restore?access_token=" + token;
Encoding encoding = Encoding.Default;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
request.Method = "post";
request.KeepAlive = true;
string str = "image=" + HttpUtility.UrlEncode(strbaser64);
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.Default);
string result = reader.ReadToEnd();
return result;
}
三、效果测试
1、页面:
2、识别结果:
2.1
2.2
2.3
四、使用结果
从上图可以看出,百度的拉伸图片恢复技术还是不错的,基本上能将图片恢复成正常的比例,让人看后感觉顺眼多了。