Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Google Cloud函数使用Vision API从图像中提取文本_Node.js_Google Cloud Functions_Google Vision - Fatal编程技术网

Node.js Google Cloud函数使用Vision API从图像中提取文本

Node.js Google Cloud函数使用Vision API从图像中提取文本,node.js,google-cloud-functions,google-vision,Node.js,Google Cloud Functions,Google Vision,我将按照教程从以下位置的图像中提取文本: 但我不希望翻译文本,我希望检测并保存文本 本教程实现了3个功能: gcloud beta functions deploy ocr-extract --trigger-bucket [YOUR_IMAGE_BUCKET_NAME] --entry-point processImage gcloud beta functions deploy ocr-translate --trigger-topic [YOUR_TRANSLATE_TOPIC_NAM

我将按照教程从以下位置的图像中提取文本:

但我不希望翻译文本,我希望检测并保存文本

本教程实现了3个功能:

gcloud beta functions deploy ocr-extract --trigger-bucket [YOUR_IMAGE_BUCKET_NAME] --entry-point processImage

gcloud beta functions deploy ocr-translate --trigger-topic [YOUR_TRANSLATE_TOPIC_NAME] --entry-point translateText

gcloud beta functions deploy ocr-save --trigger-topic [YOUR_RESULT_TOPIC_NAME] --entry-point saveResult
我只想检测文本并保存文本,但无法删除下面代码的翻译部分:

/**
 * Detects the text in an image using the Google Vision API.
 *
 * @param {string} bucketName Cloud Storage bucket name.
 * @param {string} filename Cloud Storage file name.
 * @returns {Promise}
 */
function detectText (bucketName, filename) {
  let text;

  console.log(`Looking for text in image ${filename}`);
  return vision.textDetection({ source: { imageUri: `gs://${bucketName}/${filename}` } })
    .then(([detections]) => {
      const annotation = detections.textAnnotations[0];
      text = annotation ? annotation.description : '';
      console.log(`Extracted text from image (${text.length} chars)`);
      return translate.detect(text);
    })
    .then(([detection]) => {
      if (Array.isArray(detection)) {
        detection = detection[0];
      }
      console.log(`Detected language "${detection.language}" for ${filename}`);

      // Submit a message to the bus for each language we're going to translate to
      const tasks = config.TO_LANG.map((lang) => {
        let topicName = config.TRANSLATE_TOPIC;
        if (detection.language === lang) {
          topicName = config.RESULT_TOPIC;
        }
        const messageData = {
          text: text,
          filename: filename,
          lang: lang,
          from: detection.language
        };

        return publishResult(topicName, messageData);
      });

      return Promise.all(tasks);
    });
}
之后,我只想将detectec文本保存到一个文件中,如下代码所示:

/**
 * Saves the data packet to a file in GCS. Triggered from a message on a Pub/Sub
 * topic.
 *
 * @param {object} event The Cloud Functions event.
 * @param {object} event.data The Cloud Pub/Sub Message object.
 * @param {string} event.data.data The "data" property of the Cloud Pub/Sub
 * Message. This property will be a base64-encoded string that you must decode.
     */
exports.saveResult = (event) => {
  const pubsubMessage = event.data;
  const jsonStr = Buffer.from(pubsubMessage.data, 'base64').toString();
  const payload = JSON.parse(jsonStr);

  return Promise.resolve()
    .then(() => {
      if (!payload.text) {
        throw new Error('Text not provided. Make sure you have a "text" property in your request');
      }
      if (!payload.filename) {
        throw new Error('Filename not provided. Make sure you have a "filename" property in your request');
      }
      if (!payload.lang) {
        throw new Error('Language not provided. Make sure you have a "lang" property in your request');
      }

      console.log(`Received request to save file ${payload.filename}`);

      const bucketName = config.RESULT_BUCKET;
      const filename = renameImageForSave(payload.filename, payload.lang);
      const file = storage.bucket(bucketName).file(filename);

      console.log(`Saving result to ${filename} in bucket ${bucketName}`);

      return file.save(payload.text);
    })
    .then(() => {
      console.log(`File saved.`);
    });
};

因此,那里的教程基于更为“复杂”的设置(也使用Pub-Sub和Translate),您只想提取文本,因此,有了它,您应该能够:

'use strict';
const Storage = require('@google-cloud/storage');
const Vision = require('@google-cloud/vision');
const bucketName = 'YOUR_BUCKET';
const srcFilename = 'YOUR_IMAGE.jpg';
const projectId = 'YOUR_PROJECT_ID';
const storage = new Storage({
    projectId: projectId
});
const vision = new Vision.ImageAnnotatorClient({
    projectId: projectId
});
exports.processImage = (req, res) => {
    let text;
    vision.textDetection(`gs://${bucketName}/${srcFilename}`)
        .then(([detections]) => {
            const annotation = detections.textAnnotations[0];
            text = annotation ? annotation.description : '';
            console.log(`Extracted text: ${text}`);
            console.log(`Extracted text from image (${text.length} chars)`);
        }).catch(vis_err => {
            console.error("Vision error:" , vis_err);
        });
    res.status(200).send("OK");
}
我的依赖项,在我的
package.json
文件中:

  "dependencies": {
    "@google-cloud/vision": "0.21.0"
  },

如果愿意,您可以稍后扩展此功能,将此文本保存到存储器中。还有其他教程介绍如何执行此操作

因此,那里的教程基于更为“复杂”的设置(也使用Pub-Sub和Translate),您只想提取文本,因此,有了它,您应该能够:

'use strict';
const Storage = require('@google-cloud/storage');
const Vision = require('@google-cloud/vision');
const bucketName = 'YOUR_BUCKET';
const srcFilename = 'YOUR_IMAGE.jpg';
const projectId = 'YOUR_PROJECT_ID';
const storage = new Storage({
    projectId: projectId
});
const vision = new Vision.ImageAnnotatorClient({
    projectId: projectId
});
exports.processImage = (req, res) => {
    let text;
    vision.textDetection(`gs://${bucketName}/${srcFilename}`)
        .then(([detections]) => {
            const annotation = detections.textAnnotations[0];
            text = annotation ? annotation.description : '';
            console.log(`Extracted text: ${text}`);
            console.log(`Extracted text from image (${text.length} chars)`);
        }).catch(vis_err => {
            console.error("Vision error:" , vis_err);
        });
    res.status(200).send("OK");
}
我的依赖项,在我的
package.json
文件中:

  "dependencies": {
    "@google-cloud/vision": "0.21.0"
  },

如果愿意,您可以稍后扩展此功能,将此文本保存到存储器中。还有其他教程介绍如何执行此操作

如果你对这些示例有问题,我可以提供帮助。谢谢,但我不希望在本地安装库,我希望在谷歌云中作为一个函数运行翻译。。。我试图使用你发送的链接中的代码,但由于我不是js专家,所以无法使用。教程和示例使用相同的库,可以在谷歌云上运行。您更愿意使用Go、Java、.NET、PHP、Python还是Ruby来实现这一点?Torry Yang感谢您的帮助。pythonar您是否仍在尝试使用此代码,还是已迁移到Python@克里斯蒂亚纳斯。帕拉代伊将遵循以下原则:如果您对这些示例有问题,我可以提供帮助。谢谢,但我不希望在本地安装库,我希望在谷歌云中作为一个函数运行翻译。。。我试图使用你发送的链接中的代码,但由于我不是js专家,所以无法使用。教程和示例使用相同的库,可以在谷歌云上运行。您更愿意使用Go、Java、.NET、PHP、Python还是Ruby来实现这一点?Torry Yang感谢您的帮助。pythonar您是否仍在尝试使用此代码,还是已迁移到Python@克里斯蒂安娜·帕拉达