ai圖片隨意拉伸變形(ai怎麼拉伸圖片不變形)

原文連結:
       https://ai.baidu.com/forum/topic/show/953780

一、功能描述

當我們看電影的時候,有時候如果電影的比例不對,會發現電影看的相當彆扭。同理,當我們看一張圖片時,如果感到這張圖片讓人看起來很彆扭,那就有可能是這張圖片的長寬比例不對,這時候就可以採取百度拉伸圖片恢復技術,將影象內容恢復成正常比例。

二、使用攻略

說明:本文采用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

四、使用結果

從上圖可以看出,百度的拉伸圖片恢復技術還是不錯的,基本上能將圖片恢復成正常的比例,讓人看後感覺順眼多了。