2
votes

I believe this is a simple question. When using the Watson API via Python, I have no issues running it to detect an image URL. However, I do have trouble doing it for local picture files.

My code:

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)

The error output is:

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'

I am using rodeo IDE. I have tried changing the working directory to the image folder or inputting C:/... etc., but neither of these work.

I believe it is the way I pass the argument, can someone guide me?

Essentially, what does

AttributeError: 'str' object has no attribute 'name'

Mean?

2

2 Answers

3
votes

you have to pass it a file not the name of the file. so try:

img2 = instance.classify(images_file=open('a.jpg', 'rb'))

notice that now you're passing a file object with open('a.jpg', 'rb') rather than a str object 'a.jpg' To answer the question about the error, python str objects don't have name attributes, which is exactly what the error is saying.

refer to the example at the watson python sdk github: visual recognition example

1
votes

ok, so:

file = open('img_to_classify.jpg', 'rb')
img2 = instance.classify(images_file=file)
print(img2)