刚刚开始探索Google Cloud Vision API。从他们的指南:
const client = new vision.ImageAnnotatorClient();
const fileName = 'Local image file, e.g. /path/to/image.png';
const [result] = await client.textDetection(fileName);
但是,我想使用二进制图像数据的base64表示形式,因为他们声称可以使用。
我在SO上找到此参考:Google Vision API Text Detection with Node.js set Language hint
我使用imageUri
代替了"content": string
,而不是here。但是SO示例使用const [result] = await client.batchAnnotateImages(request);
方法。我尝试对const [result] = await client.textDetection(
方法使用相同的技术,但它给了我一个错误。
所以我的问题是:是否可以使用base64编码的字符串表示图像以执行TEXT_DETECTION?如果是这样,如何?
非常感谢任何帮助。
[content
字段必须为Buffer
。
您使用nodejs客户端库。该库在内部使用grpc API,并且grpc API期望bytes
字段为content
类型。
但是,JSON API需要base64 string
。
https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#imagehttps://googleapis.dev/nodejs/vision/latest/v1.ImageAnnotatorClient.html#textDetection
您可以使用quickstart指南,然后在其中创建以下内容的地方将client创建后的行编辑为以下内容:
// Value of the image in base64
const img_base64 = '/9j/...';
const request = {
image: {
content: Buffer.from(img_base64, 'base64')
}
};
const [result] = await client.textDetection(request);
console.log(result.textAnnotations);
console.log(result.fullTextAnnotation);
您可以看一下函数here,阅读请求参数的描述,特别是以下部分:
如果键为
content
,则该值应为缓冲区。
这将导致从以前的示例代码中使用的结构。与使用imageUri
或filename
时相反,后者必须位于另一个键为source
的对象内部,如sample中所示。