我相信这是一个简单的问题。通过Python使用Watson API时,运行它来检测图像URL没有问题。但是,我确实无法为本地图片文件执行此操作。
我的代码:
from watson_developer_cloud import VisualRecognitionV3 as vr
instance = vr('2016-05-20', api_key='Your-Api-key')
img2 = instance.classify(images_file='a.jpg')
print(img2)
错误输出为:
AttributeError: 'str' object has no attribute 'name'
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-173-79c8a4eee873> in <module>()
----> 1 img2 = instance.classify(images_file='a.jpg') C:\Program Files\Anaconda3\lib\site-packages\watson_developer_cloud\visual_recognition_v3.py in classify(self, images_file, images_url, classifier_ids, owners, threshold)
154 'owners': owners, 'threshold': threshold}
155 return self._image_call('/v3/classify', images_file, images_url,
--> 156 params)
157
158 def detect_faces(self, images_file=None, images_url=None): C:\Program Files\Anaconda3\lib\site-packages\watson_developer_cloud\visual_recognition_v3.py in _image_call(self, url, images_file, images_url, params)
124 accept_json=True)
125 else:
--> 126 filename = images_file.name
127 mime_type = mimetypes.guess_type(
128 filename)[0] or 'application/octet-stream'
AttributeError: 'str' object has no attribute 'name'
我正在使用rodeo IDE。我尝试将工作目录更改为图像文件夹或输入C:/...
等,但这些都不起作用。
我相信这是我通过论证的方式,有人可以指导我吗?
基本上,
是什么AttributeError: 'str' object has no attribute 'name'
意味着什么?
答案 0 :(得分:2)
你必须传递一个不是文件名的文件。所以试试:
img2 = instance.classify(images_file=open('a.jpg', 'rb'))
请注意,现在您传递的文件对象为open('a.jpg', 'rb')
而不是str对象'a.jpg'
要回答有关错误的问题,python str
对象没有name
属性,这正是错误所说的。
参考watson python sdk github中的示例:visual recognition example
答案 1 :(得分:0)
好的,所以:
file = open('img_to_classify.jpg', 'rb')
img2 = instance.classify(images_file=file)
print(img2)