电报机器人和Google Cloud Vision的使用

大家好!最近,我写了一篇有关将我的机器人与IBM Watson集成的文章,在本文中,我将考虑与Google Cloud Vision集成以识别猫,并更详细地描述我的机器人的内部。

一点背景:

我的机器人使用IBM Watson识别成功运行了几个月,但随后在中心出现了一篇有关google cloud vision的文章,结果证明Google识别图像的能力比IBM更好。当天,我注册了Google云平台开发者的控制台,并开始在我的机器人中重写cat审核块。

经过一番搜索,我在C#上的GoogleCloudPlatform github上找到了一个合适的示例我更改了示例中的身份验证,并通过带有私钥的json文件进行了身份验证,并将其放入控制台的“服务帐户”部分。

C#中的授权码
private VisionService service;
        private string _JsonPath = @"C:\BOTS\fcatsbot\json.json";       
        private VisionService CreateAuthorizedClient(string JsonPath)
        {
            GoogleCredential credential =
                GoogleCredential.FromStream(new FileStream(JsonPath, FileMode.Open));            
            // Inject the Cloud Vision scopes
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    VisionService.Scope.CloudPlatform
                });
            }
            var res = new VisionService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                GZipEnabled = false
            });
            return res;
        }


接下来,我重新调整图像的适度性(标签检测)。在github示例中,DetectLabels使用文件,并且我必须使用从电报服务器接收到的链接,以便不存储图像文件。我只将file_id保存在数据库中,这大大提高了速度。

标签检测码
 private async Task<IList<AnnotateImageResponse>> DetectLabels(
            VisionService vision, string imageUrl)
        {
            // Convert image to Base64 encoded for JSON ASCII text based request   
            MemoryStream ms = new MemoryStream();
            using (var client = new HttpClient())
            {
                Stream imageBytes = await client.GetStreamAsync(imageUrl);
                imageBytes.CopyTo(ms);
            }
            byte[] imageArray = ms.ToArray();
            string imageContent = Convert.ToBase64String(imageArray);
            // Post label detection request to the Vision API
            // [START construct_request]
            var responses = vision.Images.Annotate(
                new BatchAnnotateImagesRequest()
                {
                    Requests = new[] {
                    new AnnotateImageRequest() {
                        Features = new []
                        { new Feature()
                            { Type =
                          "LABEL_DETECTION"}
                            },
                        Image = new Image() { Content = imageContent }
                    }
               }
                }).Execute();
            ms.Dispose();
            return responses.Responses;
        }

然后,我在“响应”中搜索是否有描述猫的标签,评级超过0.6,因此,我确定转移到机器人中的图片中是否有猫:

使用标签
foreach (var response in responses.Responses)
{
  foreach (var label in response.LabelAnnotations)
  {
    double _score = label.Score == null ? 0 : Convert.ToDouble(label.Score.Value);
    var class = label.Description.Trim();
    if (class .Contains("kitten") || class .Contains("cat") ) && (_score > 0.60))
    {
      HasCatOrKittenClass = true;//moderation OK
    }
  }
}


这是使用Telegram API从file_id获取图像链接的代码,我在C#telegram bot中使用了该库

电报getFile
var file = await MainParams.TGBot.GetFileAsync(fileid);
var file_path = file.FilePath;
var urlImage = "https://api.telegram.org/file/bot" + MainParams.bot_token + "/" + file_path;


当我使用sendPhoto将图像发送给用户时,我只是将保存的file_id传递给第二个参数。

因此,事实证明,当用户发送他的猫照片进行审核(或为此使用thecatapi.com)时,我仅在数据库中保存file_id,然后使用它来获取Telegram服务器上图片的链接,并使用sendPhoto将其发送给用户。与IBM Watson相比,使用Google云视觉进行图像识别的工作更加准确

Source: https://habr.com/ru/post/zh-CN399877/


All Articles