我很难保存提供的输出。我正在使用Python并使用演示映像进行测试。我得到以下错误:
TypeError: [mid:...] + is not JSON serializable我执行的代码:
import io
import os
import json
# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types
# Instantiates a client
vision_client = vision.ImageAnnotatorClient()
# The name of the image file to annotate
file_name = os.path.join(
os.path.dirname(__file__),
'demo-image.jpg') # Your image path from current directory
# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
# Performs label detection on the image file
response = vision_client.label_detection(image=image)
labels = response.label_annotations
print('Labels:')
for label in labels:
print(label.description, label.score, label.mid)
with open('labels.json', 'w') as fp:
json.dump(labels, fp)输出显示在屏幕上,但是我不知道如何保存它。有人有什么建议吗?
发布于 2018-12-12 13:24:30
也许你已经能够找到一个解决你的问题的方法(如果是这样的话,我也邀请你分享它作为你自己的帖子的答案),但无论如何,让我分享一些可能对其他有类似问题的用户有用的注释:
由于您可以使用Python中的response函数进行检查,所以labels[i]是类型的对象,而labels[i]是类型的对象。它们似乎都没有现成的实现来将它们转换为JSON,正如您正在尝试的那样,所以我认为在labels中转换每个EntityAnnotation的最简单的方法是将它们转换为Python,然后将它们分组为一个数组,并将其转换为JSON。
为此,我在代码片段中添加了一些简单的代码行:
[...]
label_dicts = [] # Array that will contain all the EntityAnnotation dictionaries
print('Labels:')
for label in labels:
# Write each label (EntityAnnotation) into a dictionary
dict = {'description': label.description, 'score': label.score, 'mid': label.mid}
# Populate the array
label_dicts.append(dict)
with open('labels.json', 'w') as fp:
json.dump(label_dicts, fp)发布于 2019-04-03 05:13:30
谷歌发布了一个图书馆
from google.protobuf.json_format import MessageToJsonwebdetect = vision_client.web_detection(blob_source) jsonObj = MessageToJson(webdetect)
发布于 2018-12-19 13:25:02
我能够使用以下函数保存输出:
# Save output as JSON
def store_json(json_input):
with open(json_file_name, 'a') as f:
f.write(json_input + '\n')正如@dsesto所提到的,我必须定义一本字典。在本词典中,我定义了我希望在输出中保存的信息类型。
with open(photo_file, 'rb') as image:
image_content = base64.b64encode(image.read())
service_request = service.images().annotate(
body={
'requests': [{
'image': {
'content': image_content
},
'features': [{
'type': 'LABEL_DETECTION',
'maxResults': 20,
},
{
'type': 'TEXT_DETECTION',
'maxResults': 20,
},
{
'type': 'WEB_DETECTION',
'maxResults': 20,
}]
}]
})https://stackoverflow.com/questions/52169264
复制相似问题