从 GCP 存储打开图像以使用 Vision 处理它们时出现类型错误 API

TypeError when opening images from GCP storage to process them with Vision API

我正在尝试 open/get public 来自 google 云存储的图像使用 Vision API 进行处理。这是我的代码。

client = vision.ImageAnnotatorClient()

for file_name in list_blobs(BUCKET_NAME):
    response = requests.get(file_name)
    content = Image.open(BytesIO(response.content))

    image = types.Image(content=content)

    response = client.label_detection(image=image)
    labels = response.label_annotations

    print('Labels:\n')
    for label in labels:
        print(label.description)

我收到以下错误

Traceback (most recent call last):
  File "/Users/gmwill934/PycharmProjects/PDFRekog/functions_vision.py", line 21, in <module>
    image = types.Image(content=content)
TypeError: <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=800x449 at 0x10BA5AD50> has type JpegImageFile, but expected one of: bytes

我很难尝试打开来自网络的图像,当我在本地有我的图像并使用 with open() as image_file....

打开时它会起作用

[编辑]

所以我修改了我的代码,我将图像转换为 bytes 类型,代码按预期运行但没有标签显示。

for file_name in list_blobs(BUCKET_NAME):
    image = imageio.imread(file_name)
    my_array = np.asarray(image)
    content = my_array.tobytes()

    image = types.Image(content=content)

    response = client.label_detection(image=image)
    labels = response.label_annotations

    print('Labels:\n')
    for label in labels:
        print(label.description)

numpy数组可以转换为字节吗?还是我还缺少其他东西。

所以 Image 期待像素的二进制表示。我通过将内容变量更改为以下内容来完成它。

content = urlopen(file_name).read()

content 现在以二进制模式返回。