【问题标题】:Python resize image and send to google vision functionPython调整图像大小并发送到谷歌视觉功能
【发布时间】:2025-12-01 03:35:01
【问题描述】:

由于谷歌视觉在输入图像大小上有一些restrictions,我想先调整输入图像的大小,然后使用detect_labels() 函数。

这是他们的sample code

def detect_labels(path):
"""Detects labels in the file."""
vision_client = vision.Client()

with io.open(path, 'rb') as image_file:
    content = image_file.read()

image = vision_client.image(content=content)

labels = image.detect_labels()
print('Labels:')

for label in labels:
    print(label.description)

他们使用io 打开图像文件。我想知道这样,如何在内存中调整图像大小,然后调用detect_labels()

【问题讨论】:

  • 当你传递一个超大的图像时,客户端会抛出任何异常吗?
  • 是的,它说图像太大:google.gax.errors.RetryError: GaxError(Exception occurred in retry method that was not classified as transient, caused by <_Rendezvous of RPC that terminated with (StatusCode.INVALID_ARGUMENT, Some image is too large)>)

标签: python-2.7 computer-vision google-cloud-vision


【解决方案1】:

您可以通过 PIL/Pillow 调整图像大小,然后将其传递给客户端:

替换

with io.open(path, 'rb') as image_file:
    content = image_file.read()

# Warning: untested code, may require some fiddling
import Image, StringIO

img = Image.open(path)
img.thumbnail((512, 512))
buffer = StringIO.StringIO()
img.save(buffer, "PNG")

content = buffer.getvalue()

【讨论】:

【解决方案2】:

python3 的代码:

致谢:@kristaps

import io
from PIL import Image
img = Image.open(path)
img.thumbnail((512, 512))
buffer = io.BytesIO()
img.save(buffer, "JPEG")
content = buffer.getvalue()

【讨论】:

    最近更新 更多