利用计算机视觉API进行图像分析的多语言实现
立即解锁
发布时间: 2025-08-17 00:19:52 阅读量: 34 订阅数: 25 AIGC 


Visual Studio Code: 跨平台开发的得力助手
### 利用计算机视觉 API 进行图像分析的多语言实现
#### 1. 获取服务密钥
无论使用何种编程语言或框架来调用计算机视觉 API,都需要获取服务密钥,这些密钥用于代码与服务进行身份验证。操作步骤如下:
1. 进入“Keys and Endpoint”页面。
2. 点击左侧的“Keys and Endpoint”项。
3. 默认情况下,密钥是隐藏的,点击“Show Keys”按钮。通常只需要 Key 1 即可,Key 2 是出于安全考虑提供的。记录下 Key 1 和 Endpoint 字段,后续编写代码时会用到。
#### 2. 使用 .NET 消费 AI 服务
以下是使用 .NET 创建控制台应用程序来进行图像分析的详细步骤:
1. **创建新项目**:
- 在 Visual Studio Code 中,通过“Terminal” -> “New Terminal”打开新的终端实例。
- 创建一个子文件夹用于存放新项目。
- 在终端中输入以下命令生成新的控制台项目:
```
> dotnet new console
```
2. **安装客户端库**:Microsoft 提供了用于 .NET 的客户端库 `Microsoft.Azure.CognitiveServices.Vision.ComputerVision`,可以简化调用计算机视觉 API 的过程。在终端中输入以下命令安装该库:
```
> dotnet add package Microsoft.Azure.CognitiveServices.Vision.ComputerVision
```
3. **设置变量和常量**:打开 `Program.cs` 文件,添加以下代码,并将 `serviceKey` 和 `endpoint` 替换为实际的计算机视觉服务密钥和端点:
```csharp
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
namespace ComputerVisionNet
{
class Program
{
static string serviceKey = "YOUR-KEY-GOES-HERE";
static string endpoint =
"https://YOUR-ENDPOINT.cognitiveservices.azure.com/";
private const string imageToAnalyze = "https://moderatorsampleimages.blob.core.windows.net/samples/sample16.png";
async static void Main(string[] args)
{
// Create a client
ComputerVisionClient client = Authenticate(endpoint, serviceKey);
// Analyze an image to get features and other properties.
await AnalyzeImageUrlAsync(client, imageToAnalyze);
}
public static ComputerVisionClient Authenticate(string endpoint, string key)
{
ComputerVisionClient client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
public static async Task AnalyzeImageUrlAsync(ComputerVisionClient client, string imageUrl)
{
// A list that defines the features to be extracted from the image.
List<VisualFeatureTypes?> features = new List<VisualFeatureTypes?>()
{
VisualFeatureTypes.Tags,
VisualFeatureTypes.Color,
VisualFeatureTypes.Description,
VisualFeatureTypes.Objects,
VisualFeatureTypes.Faces,
VisualFeatureTypes.Adult
};
Console.WriteLine($"Analyzing the image {Path.GetFileName(imageUrl)}...");
Console.WriteLine();
// Analyze the URL image
ImageAnalysis results = await client.AnalyzeImageAsync(imageUrl, visualFeatures: features);
// Adult content?
Console.WriteLine($"Is adult content?: {results.Adult.IsAdultContent}");
// Image tags and their confidence score
Console.WriteLine("Tags:");
foreach (var tag in results.Tags)
{
Console.WriteLine($"{tag.Name} {tag.Confidence}");
}
Console.WriteLine("Colors:");
Console.WriteLine($" {results.Color.AccentColor}")
```
0
0
复制全文
相关推荐









