Microsoft.Azure:語音識別/圖片識別/人臉識別/情緒識別

来源:https://www.cnblogs.com/Gao1234/archive/2018/01/03/8184948.html
-Advertisement-
Play Games

在第一篇博客里提過圖片識別的底層.最精準的圖片識別需要海量的數據磨煉.自己寫的底層沒有以億為單位的數據支持其實也是個殘廢品. 在此介紹Microsoft的幾個雲服務吧.都是付費的喔.個人可以申請30天免費試用. public class FaceHelper { private const stri ...


 

在第一篇博客里提過圖片識別的底層.最精準的圖片識別需要海量的數據磨煉.自己寫的底層沒有以億為單位的數據支持其實也是個殘廢品.

在此介紹Microsoft的幾個雲服務吧.都是付費的喔.個人可以申請30天免費試用.

public class FaceHelper
{
private const string uriBase = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect";
private static string subscriptionKey = string.Empty;
public FaceHelper(string Key,string imageFilePath)
{
if (!String.IsNullOrWhiteSpace(Key))
{
subscriptionKey = Key;
MakeAnalysisRequest(imageFilePath);
}
}

static async void MakeAnalysisRequest(string imageFilePath)
{
HttpClient client = new HttpClient();

client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

string requestParameters = "returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";

string uri = uriBase + "?" + requestParameters;

HttpResponseMessage response;

byte[] byteData = GetImageAsByteArray(imageFilePath);

using (ByteArrayContent content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

response = await client.PostAsync(uri, content);

string contentString = await response.Content.ReadAsStringAsync();

Console.WriteLine("\nResponse:\n");
Console.WriteLine(JsonPrettyPrint(contentString));
}
}

static byte[] GetImageAsByteArray(string imageFilePath)
{
FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
return binaryReader.ReadBytes((int)fileStream.Length);
}

static string JsonPrettyPrint(string json)
{
if (string.IsNullOrEmpty(json))
return string.Empty;

json = json.Replace(Environment.NewLine, "").Replace("\t", "");

StringBuilder sb = new StringBuilder();
bool quote = false;
bool ignore = false;
int offset = 0;
int indentLength = 3;

foreach (char ch in json)
{
switch (ch)
{
case '"':
if (!ignore) quote = !quote;
break;
case '\'':
if (quote) ignore = !ignore;
break;
}

if (quote)
sb.Append(ch);
else
{
switch (ch)
{
case '{':
case '[':
sb.Append(ch);
sb.Append(Environment.NewLine);
sb.Append(new string(' ', ++offset * indentLength));
break;
case '}':
case ']':
sb.Append(Environment.NewLine);
sb.Append(new string(' ', --offset * indentLength));
sb.Append(ch);
break;
case ',':
sb.Append(ch);
sb.Append(Environment.NewLine);
sb.Append(new string(' ', offset * indentLength));
break;
case ':':
sb.Append(ch);
sb.Append(' ');
break;
default:
if (ch != ' ') sb.Append(ch);
break;
}
}
}

return sb.ToString().Trim();
}

}

臉識別 API.檢測、識別、分析、組織和標記照片中的人臉

FaceHelper face = new FaceHelper("你的密鑰",ConfigurationManager.AppSettings["Face"] );

 

 

返回值很多很詳細.人臉在圖片的那個區域。性別.有沒有頭髮。有沒有鬍子。有沒有眼鏡都寫的很清楚.在此不一一列舉

以下是聲音識別.分REST 和SOCKET 語音識別也分中英美法.傳遞的音頻也要分長短.以下配置為英文識別.REST.15秒以下音頻

public class VoiceHelper
{
/// <summary>
/// 識別模式
///有認可的三種模式:interactive,conversation,和dictation。識別模式根據用戶如何說話來調整語音識別。為您的應用程式選擇適當的識別模式。
/// </summary>
public VoiceHelper(string file,string key)
{
string url = "https://speech.platform.bing.com/speech/recognition/dictation/cognitiveservices/v1?language=en-US&format=simple";

string responseString = string.Empty;
HttpWebRequest request = null;
request = (HttpWebRequest)HttpWebRequest.Create(url);
request.SendChunked = true;
request.Accept = @"application/json;text/xml";
request.Method = "POST";
request.ProtocolVersion = HttpVersion.Version11;
request.ContentType = @"audio/wav; codec=audio/pcm; samplerate=16000";
request.Headers["Ocp-Apim-Subscription-Key"] = key;

using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{

byte[] buffer = null;
int bytesRead = 0;
using (Stream requestStream = request.GetRequestStream())
{

buffer = new Byte[checked((uint)Math.Min(1024, (int)fs.Length))];
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}

requestStream.Flush();
}
}

using (WebResponse response = request.GetResponse())
{
Console.WriteLine(((HttpWebResponse)response).StatusCode);

using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}

Console.WriteLine(responseString);
}


}
}

 

 

 

 

VoiceHelper voice = new VoiceHelper(@ConfigurationManager.AppSettings["Voice"], "你的密鑰");

 

 

 

 

 這個語音識別還是可以的.Displaytext就是我在音頻中說的話.重覆了三遍 TEST.聲音很沙啞也很低沉.識別率很贊.

不過要註意只支持15秒帶有PCM單聲道(單聲道),16 KHz的WAV文件

以下是圖片識別.這個就可好玩了.我放了一個大飛機.返回的數據中.飛機藍天都識別了

 

public class OCRHelper
{
const string subscriptionKey = "你的密鑰";

const string uriBase = "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/analyze";

public OCRHelper(string file)
{
// Get the path and filename to process from the user.
Console.WriteLine("Analyze an image:");
Console.Write("Enter the path to an image you wish to analzye: ");

// Execute the REST API call.
MakeAnalysisRequest(file);

Console.WriteLine("\nPlease wait a moment for the results to appear. Then, press Enter to exit...\n");

}
/// <summary>
/// Gets the analysis of the specified image file by using the Computer Vision REST API.
/// </summary>
/// <param name="imageFilePath">The image file.</param>
static async void MakeAnalysisRequest(string imageFilePath)
{
HttpClient client = new HttpClient();

// Request headers.
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

// Request parameters. A third optional parameter is "details".
string requestParameters = "visualFeatures=Categories,Description,Color&language=en";

// Assemble the URI for the REST API Call.
string uri = uriBase + "?" + requestParameters;

HttpResponseMessage response;

// Request body. Posts a locally stored JPEG image.
byte[] byteData = GetImageAsByteArray(imageFilePath);

using (ByteArrayContent content = new ByteArrayContent(byteData))
{
// This example uses content type "application/octet-stream".
// The other content types you can use are "application/json" and "multipart/form-data".
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

// Execute the REST API call.
response = await client.PostAsync(uri, content);

// Get the JSON response.
string contentString = await response.Content.ReadAsStringAsync();

// Display the JSON response.
Console.WriteLine("\nResponse:\n");
Console.WriteLine(JsonPrettyPrint(contentString));
//description.captions.text 對圖片的英文描述
}
}


/// <summary>
/// Returns the contents of the specified file as a byte array.
/// </summary>
/// <param name="imageFilePath">The image file to read.</param>
/// <returns>The byte array of the image data.</returns>
static byte[] GetImageAsByteArray(string imageFilePath)
{
FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
return binaryReader.ReadBytes((int)fileStream.Length);
}


/// <summary>
/// Formats the given JSON string by adding line breaks and indents.
/// </summary>
/// <param name="json">The raw JSON string to format.</param>
/// <returns>The formatted JSON string.</returns>
static string JsonPrettyPrint(string json)
{
if (string.IsNullOrEmpty(json))
return string.Empty;

json = json.Replace(Environment.NewLine, "").Replace("\t", "");

StringBuilder sb = new StringBuilder();
bool quote = false;
bool ignore = false;
int offset = 0;
int indentLength = 3;

foreach (char ch in json)
{
switch (ch)
{
case '"':
if (!ignore) quote = !quote;
break;
case '\'':
if (quote) ignore = !ignore;
break;
}

if (quote)
sb.Append(ch);
else
{
switch (ch)
{
case '{':
case '[':
sb.Append(ch);
sb.Append(Environment.NewLine);
sb.Append(new string(' ', ++offset * indentLength));
break;
case '}':
case ']':
sb.Append(Environment.NewLine);
sb.Append(new string(' ', --offset * indentLength));
sb.Append(ch);
break;
case ',':
sb.Append(ch);
sb.Append(Environment.NewLine);
sb.Append(new string(' ', offset * indentLength));
break;
case ':':
sb.Append(ch);
sb.Append(' ');
break;
default:
if (ch != ' ') sb.Append(ch);
break;
}
}
}

return sb.ToString().Trim();
}
}

 

 OCRHelper ocr = new OCRHelper(@"C:\Users\Administrator\Desktop\test2.png");

 下圖是輸入參數

 

 

 下麵是輸出參數

 

 一隻大鳥在天上飄

 情緒識別的介面就不解釋了.人臉識別做的比情緒識別還詳細.

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Python是一種解釋型、面向對象、動態數據類型的高級程式設計語言。 像Perl語言一樣,Python源代碼同樣遵循GPL(GUN General Public License)協議。 我目前學習的是Python2.x版本。 接下來我來說一說Python的特點 1.易於學習:有相對較少的關鍵字,結構 ...
  • 1.Flask: Flask是一個基於Python開發並且依賴jinja2模板和Werkzeug WSGI服務的一個微型框架,對於Werkzeug本質是Socket服務端,其用於接收http請求並對請求進行預處理,然後觸發Flask框架,開發人員基於Flask框架提供的功能對請求進行相應的處理,並返 ...
  • public static void main(String[] args) { for (int i = 0; i < 5; i++) { for (int j = 0; j < 10; j++) { System.out.print(" "); } for (int j = 0; j <5-i; ...
  • 1.當使用轉發時,JSP容器將使用一個內部方法來調用目標頁面,新的頁面繼續處理同一個請求,而瀏覽器不會知道這個過程; 2.重定向是第一個頁面通知瀏覽器發送一個新的頁面請求. 3.轉發不改變URL,重定向回改變URL; 4.因為瀏覽器要發出新請求,故而重定向慢一些; 5.由於發生了新請求,故而重定向之 ...
  • 自動調用Spring的bean.xml配置文件 需要web.xml啟動文件 代碼如下: 其中調用了過濾器和監聽器 Spring核心配置文件bean.xml代碼 配置文件註入對象屬性,註意需要類當中聲明屬性並設置setter方法 層層調用 UserAction類代碼如下: UserService類代碼 ...
  • 背水一戰 Windows 10 之 用戶和賬號: 數據賬號的添加和管, OAuth 2.0 驗證 ...
  • 使用方法: 給委托賦值的幾種方式 //調用委托的方法 noreturn.Invoke() 上面展示的是委托的基本定義於使用方法,在mvc中基本摒棄了這種寫法,轉而使用封裝好的泛型委托來使用 使用方法: 下麵寫幾個簡單的demo演示一下 下麵來調用這個方法,看一下委托的具體使用方法 上面就是一個簡單但 ...
  • “工具善其事,必先利其器!裝好這些插件讓vs更上一層樓” ReSharper : 首先的是Resharper,這個基本是目前是我開發過程中必備的工具集,唯一的缺點就是吃記憶體,所以你的記憶體要是低於8G,就不要使用它了。它的特點可以快速重構、高亮顯示錯誤、導航和搜索都很方便、智能提示、智能複製這個我特別 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...