API обнаружения текста Google - результат веб-демонстрации отличается от использования API

Я попытался использовать функцию обнаружения текста Google Vision API и веб-демонстрацию Google для распознавания текста в моем изображении. Два результата - это не одно и то же.

Во-первых, я попробовал это с демонстрацией по адресу: https://cloud.google.com/vision/docs/drag-and-drop. Наконец, я попробовал это с кодом API Google на языке Python. Два результата - это не одно и то же, и я не знаю почему. Не могли бы вы помочь мне с этой проблемой?

мой код Python здесь:

client = vision.ImageAnnotatorClient()
raw_byte = cv2.imencode('.jpg', image)[1].tostring()
post_image = types.Image(content=raw_byte)
image_context = vision.types.ImageContext()
response = client.text_detection(image=post_image, image_context=image_context)

person Thien Vu Pham Cung Le    schedule 12.07.2019    source источник
comment
Попробуйте использовать document_text_detection и посмотрите, есть ли разница в выводе cloud.google.com/ видение / документы /   -  person Christopher    schedule 12.07.2019
comment
Я попробовал, и результат полностью отличался от моих ожиданий. Это не то же самое, что веб-демонстрация   -  person Thien Vu Pham Cung Le    schedule 12.07.2019


Ответы (2)


Это код Typescript.

Но идея состоит не в том, чтобы использовать text_detection, а в том, чтобы использовать что-то вроде document_text_detection (не знаю, что конкретно предоставляет python API).

Использование documentTextDetection() вместо textDetection() решило для меня ту же проблему.

const fs = require("fs");
const path = require("path");
const vision = require("@google-cloud/vision");

async function quickstart() {
  let text = '';
  const fileName = "j056vt-_800w_800h_sb.jpg";
  const imageFile = fs.readFileSync(fileName);
  const image = Buffer.from(imageFile).toString("base64");
  const client = new vision.ImageAnnotatorClient();

  const request = {
    image: {
      content: image
    },
    imageContext: {
      languageHints: ["vi-VN"]
    }
  };

  const [result] = await client.documentTextDetection(request);

  // OUTPUT METHOD A

  for (const tmp of result.textAnnotations) {
      text += tmp.description + "\n";
  }

  console.log(text);

  const out = path.basename(fileName, path.extname(fileName)) + ".txt";
  fs.writeFileSync(out, text);

  // OUTPUT METHOD B

  const fullTextAnnotation = result.fullTextAnnotation;
  console.log(`Full text: ${fullTextAnnotation.text}`);
  fullTextAnnotation.pages.forEach(page => {
    page.blocks.forEach(block => {
      console.log(`Block confidence: ${block.confidence}`);
      block.paragraphs.forEach(paragraph => {
        console.log(`Paragraph confidence: ${paragraph.confidence}`);
        paragraph.words.forEach(word => {
          const wordText = word.symbols.map(s => s.text).join("");
          console.log(`Word text: ${wordText}`);
          console.log(`Word confidence: ${word.confidence}`);
          word.symbols.forEach(symbol => {
            console.log(`Symbol text: ${symbol.text}`);
            console.log(`Symbol confidence: ${symbol.confidence}`);
          });
        });
      });
    });
  });

}

quickstart();
person Dabbel    schedule 14.11.2019

На самом деле, сравнивая оба ваших результата, я вижу единственную разницу в том, как они отображаются. Сайт Google Cloud Drag and Drop отображает результаты с ограничивающими рамками и пытается найти области текста.

Ответ, который вы получите с помощью сценария python, содержит ту же информацию. Несколько примеров:

texts = response.text_annotations
print([i.description for i in texts])
# prints all the words that were found in the image

print([i.bounding_poly.vertices for i in texts])
# prints all boxes around detected words

Не стесняйтесь задавать дополнительные вопросы для уточнения.

Еще несколько мыслей:

  • Вы предварительно обрабатываете свои изображения?
  • Какого размера изображения?
person Patrick_Weber    schedule 18.07.2019