在 Python 中读取和使用 url 请求的图像
Read and use image requested from url in Python
我目前正在尝试使用 Google 的 python 视觉库。但我目前卡在如何从网络上读取图像上。到目前为止,我已经在下面得到了这个。我的问题是内容似乎总是空的,当我使用 PyCharm 检查时,它说它只包含 b''
。
如何打开此图片以便将其用于 Google 的库?
from google.cloud import vision
from google.cloud.vision import types
from urllib import request
import io
client = vision.ImageAnnotatorClient.from_service_account_json('cred.json')
url = "https://cdn.getyourguide.com/img/location_img-59-1969619245-148.jpg"
img = request.urlopen(url)
with io.open('location_img-59-1969619245-148.jpg', 'rb') as fhand:
content = fhand.read()
image = types.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
print('Labels:')
for label in labels:
print(label.description)
你尝试通过 requests 库获取图像吗?
import requests
r = requests.get("https://cdn.getyourguide.com/img/location_img-59-1969619245-148.jpg")
o = open("location_img.jpg", "wb")
o.write(r.content)
o.close()
我目前正在尝试使用 Google 的 python 视觉库。但我目前卡在如何从网络上读取图像上。到目前为止,我已经在下面得到了这个。我的问题是内容似乎总是空的,当我使用 PyCharm 检查时,它说它只包含 b''
。
如何打开此图片以便将其用于 Google 的库?
from google.cloud import vision
from google.cloud.vision import types
from urllib import request
import io
client = vision.ImageAnnotatorClient.from_service_account_json('cred.json')
url = "https://cdn.getyourguide.com/img/location_img-59-1969619245-148.jpg"
img = request.urlopen(url)
with io.open('location_img-59-1969619245-148.jpg', 'rb') as fhand:
content = fhand.read()
image = types.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
print('Labels:')
for label in labels:
print(label.description)
你尝试通过 requests 库获取图像吗?
import requests
r = requests.get("https://cdn.getyourguide.com/img/location_img-59-1969619245-148.jpg")
o = open("location_img.jpg", "wb")
o.write(r.content)
o.close()