Curl Node Java Python

Visual Recognition

API Reference

Introduction

The IBM Watson™ Visual Recognition service uses deep learning algorithms to identify scenes, objects, and celebrity faces in images you upload to the service. You can create and train a custom classifier to identify subjects that suit your needs.

Descriptions of Node classes referred to in this reference are available in the Node documentation for the Watson Developer Cloud Node.js SDK.

Descriptions of Java classes referred to in this reference are available in the Javadoc for the Watson Developer Cloud Java SDK.

Descriptions of Python classes referred to in this reference are available in the Python documentation for the Watson Developer Cloud Python SDK.

API Endpoint

https://gateway-a.watsonplatform.net/visual-recognition/api

Important: If you have Bluemix Dedicated, this may not be your service endpoint. Double check your endpoint URL on the Service Credentials page in your instance of the Visual Recognition Service on Bluemix.

npm

npm install watson-developer-cloud --save

pip

pip install --upgrade watson-developer-cloud

API explorer

To interact with this API, use the Visual Recognition Service API explorer. Use the explorer to test your calls to the API, and to view live responses from the server.

Authentication

You authenticate to the Visual Recognition API by providing the API key that is provided in the service credentials for the service instance that you want to use.

After you create an instance of the Visual Recognition service, you can view the API key by selecting Service Credentials from the left pane of the service dashboard.

Replace {api-key} with your API key.

curl "https://gateway-a.watsonplatform.net/visual-recognition/api/{endpoint}?api_key={api-key}"
var watson = require('watson-developer-cloud');
var visual_recognition = watson.visual_recognition({
  api_key: '{api-key}',
  version_date: '2016-05-20'
});
VisualRecognition service = new VisualRecognition();
service.setAPIKey("{api-key}");

import line to: from /usr/local/lib/python2.7/dist-packages/watson_developer_cloud import VisualRecognitionV3 as VisualRecognition

visual_recognition = VisualRecognition(
    api_key='{api-key}')

Methods

Classify an image

Upload images or URLs to identify classes by default. To identify custom classifiers, include the classifier_ids or owners parameters. Images must be in .jpeg, or .png format.

For each image, the response includes a score for each class within each selected classifier. Scores range from 0 - 1 with a higher score indicating greater likelihood of the class being depicted in the image. The default threshold for reporting scores from a classifier is 0.5. We recommend an image that is a minimum of 224 x 224 pixels for best quality results.

GET /v3/classify
POST /v3/classify

GET Request

Use GET /v3/classify to classify URLs against classifiers as a query parameter.

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
url query (Required for GET) The URL of an image (.jpg, or .png). Redirects are followed, so you can use shortened URLs. The resolved URL is returned in the response. Maximum image size is 2 MB.
owners query A comma-separated list with the value(s) "IBM" and/or "me" to specify which classifiers to run.
classifier_ids query A comma-separated list of the classifier IDs used to classify the images. "default" is the classifier_id of the built-in classifier. A specialty "food" classifier is also available.
threshold query A floating value that specifies the minimum score a class must have to be displayed in the response. Setting the threshold to 0.0 will return all values, regardless of their classification score.
Accept-Language header Specifies the language of the output. You can specify en for English, es for Spanish, ar for Arabic, or ja for Japanese. Classifiers for which no translation is available are ommitted.

Example GET request

https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key={api-key}&url=https://github.com/watson-developer-cloud/doc-tutorial-downloads/raw/master/visual-recognition/fruitbowl.jpg&version=2016-05-19

To quickly try out the API, copy the GET into the the URL bar of your browser, replace {api-key} with your API key from Bluemix, and press enter.

POST Request

Use POST /v3/classify to upload a single image, URL, or a compressed (.zip) file of multiple images. You can analyze images against classifiers or against an array of classifier IDs you upload in a JSON file.

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
images_file multipart/form-data (Required) The image file (.jpg, or .png) or compressed (.zip) file of images to classify. The max number of images in a .zip file is limited to 20, and limited to 5 MB.
parameters multipart/form-data A JSON file containing input parameters that you can use to specify specific classifiers to call against, and classifier confidence scores. Input parameters can include:
  • classifier_ids - An array of classifier IDs to classify the images against.
  • owners - An array with the value(s) "IBM" and/or "me" to specify which classifiers to run.
  • threshold - A floating point value that specifies the minimum score a class must have to be displayed in the response.
Accept-Language Header Specifies the language of the output. You can specify en for English, es for Spanish, or ar for Arabic. Classifiers for which no translation is available are ommitted.

Example POST request

curl -X POST -F "images_file=@fruitbowl.jpg" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key={api-key}&version=2016-05-20"

Example POST request with a parameters JSON

curl -X POST -F "images_file=@fruitbowl.jpg" -F "parameters=@fruit.json" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key={api-key}&version=2016-05-20"

Example JSON file

{  
   "classifier_ids":[  
      "fruits_1462128776",
      "SatelliteModel_6242312846"
   ],
   "threshold":0.6
}
Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
images_file multipart/form-data (Required) The image file (.jpg, or .png) or compressed (.zip) file of images to classify. The max number of images in a .zip file is limited to 20, and limited to 5 MB.
parameters multipart/form-data A JSON file containing input parameters. Input parameters can include:
  • url - A string with the image URL to analyze.
  • classifier_ids - An array of classifier IDs to classify the images against.
  • owners - An array with the value(s) "IBM" and/or "me" to specify which classifiers to run.
  • threshold - A floating point value that specifies the minimum score a class must have to be displayed in the response.
Accept-Language Header Specifies the language of the output. You can specify en for English, es for Spanish, ar for Arabic, or ja for Japanese. Classifiers for which no translation is available are ommitted.

Example request

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-20'
});

var params = {
  images_file: fs.createReadStream('./resources/car.png')
};

visual_recognition.classify(params, function(err, res) {
  if (err)
    console.log(err);
  else
    console.log(JSON.stringify(res, null, 2));
});
Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
images_file multipart/form-data (Required) The image file (.jpg, or .png) or compressed (.zip) file of images to classify. The max number of images in a .zip file is limited to 20, and limited to 5 MB.
parameters multipart/form-data A JSON file containing input parameters. Input parameters can include:
  • url - A string with the image URL to analyze.
  • classifier_ids - An array of classifier IDs to classify the images against.
  • owners - An array with the value(s) "IBM" and/or "me" to specify which classifiers to run.
  • threshold - A floating point value that specifies the minimum score a class must have to be displayed in the response.
Accept-Language Header Specifies the language of the output. You can specify en for English, es for Spanish, ar for Arabic, or ja for Japanese. Classifiers for which no translation is available are ommitted.

Example request

VisualRecognition service = new VisualRecognition(VisualRecognition.VERSION_DATE_2016_05_19);
service.setApiKey("{api-key}");

System.out.println("Classify an image");
ClassifyImagesOptions options = new ClassifyImagesOptions.Builder()
    .images(new File("src/test/resources/visual_recognition/car.png"))
    .build();
VisualClassification result = service.classify(options).execute();
System.out.println(result);
Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
images_file multipart/form-data (Required) The image file (.jpg, or .png) or compressed (.zip) file of images to classify. The max number of images in a .zip file is limited to 20, and limited to 5 MB.
parameters multipart/form-data A JSON file containing input parameters. Input parameters can include:
  • url - A string with the image URL to analyze.
  • classifier_ids - An array of classifier IDs to classify the images against.
  • owners - An array with the value(s) "IBM" and/or "me" to specify which classifiers to run.
  • threshold - A floating point value that specifies the minimum score a class must have to be displayed in the response.
Accept-Language Header Specifies the language of the output. You can specify en for English, es for Spanish, ar for Arabic, or ja for Japanese. Classifiers for which no translation is available are ommitted.

Example request

import json
from os.path import join, dirname
from os import environ
from watson_developer_cloud import VisualRecognitionV3

visual_recognition = VisualRecognitionV3('2016-05-20', api_key='{api-key}')

print(json.dumps(visual_recognition.classify(images_url=https://www.ibm.com/ibm/ginni/images/ginni_bio_780x981_v4_03162016.jpg), indent=2))

Response

Name Description
images The array of images classified.
classifiers An array of the classifiers detected in the images.
classes An array of classes within a classifier.
class The name of the class identified in the image.
score The score of a class identified in the image. Scores range from 0-1, with a higher score indicating greater correlation.
classifier_id The ID of a classifier identified in the image.
name The name of the classifier identified in the image.
image The relative path of the image file. This is omitted if the image was passed by URL.
source_url The source URL of the image, before any redirects. This is omitted if the image was uploaded.
resolved_url The fully-resolved URL of the image, after redirects are followed. This is omitted if the image was uploaded.
images_processed The number of images processed by the API call.
error An object containing information about what might have caused a failure, such as an image that is too large. This is omitted if there is no error or warning.
error_id A codified string ID for a specific error. For example, "limit_exceeded".
description A human-readable error description. For example, "File size limit (1MB) exceeded".
warnings An array containing informaton about what might cause the output to be less than optimal. For example, a call with a corrupt .zip file and a list of image URLs will still complete but will not have the expected output. This is omitted if there is no warning.

Example response

{
    "images": [
        {
            "classifiers": [
                {
                    "classes": [
                        {
                            "class": "apple",
                            "score": 0.645656
                        },
                        {
                            "class": "fruit",
                            "score": 0.598688
                        },
                        {
                            "class": "food",
                            "score": 0.598688
                        },
                        {
                            "class": "orange",
                            "score": 0.5
                        },
                        {
                            "class": "vegetable",
                            "score": 0.28905
                        },
                        {
                            "class": "tree",
                            "score": 0.28905
                        }
                    ],
                    "classifier_id": "default",
                    "name": "default"
                },
                {
                    "classes": [
                        {
                            "class": "orange",
                            "score": 0.635488
                        }
                    ],
                    "classifier_id": "fruits_1050835757",
                    "name": "fruits"
                },
            ],
            "image": "orange-apple-banana-isolated.jpg"
        },
        {
            "classifiers": [
                {
                    "classes": [
                        {
                            "class": "fruit",
                            "score": 0.916827
                        },
                        {
                            "class": "vegetation",
                            "score": 0.768525
                        },
                        {
                            "class": "market",
                            "score": 0.768525
                        },
                        {
                            "class": "food",
                            "score": 0.377541
                        },
                        {
                            "class": "mercado",
                            "score": 0.28905
                        },
                        {
                            "class": "vegetable",
                            "score": 0.268941
                        }
                    ],
                    "classifier_id": "default",
                    "name": "default"
                },
                {
                    "classes": [
                        {
                            "class": "apple",
                            "score": 0.541237
                        }
                    ],
                    "classifier_id": "fruits_1050835757",
                    "name": "fruits"
                },
            ],
            "resolved_url": "https://c1.staticflickr.com/9/8803/17306765722_a2d0
be2f9e_b.jpg",
            "source_url": "https://flic.kr/p/snkGus"
        }
    ]
    "images_processed": 2
}

Detect faces

Analyze faces in images and get data about them, such as estimated age, gender, plus names of celebrities. Images must be in .jpeg, or .png format. This functionality is not trainable, and does not support general biometric facial recognition.

For each image, the response includes face location, a minimum and maximum estimated age, a gender, and confidence scores. Scores range from 0 - 1 with a higher score indicating greater correlation.

GET /v3/detect_faces
POST /v3/detect_faces

GET Request

Use GET /v3/detect_faces to detect faces in a single URL.

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
url query (Required) The URL of an image (.jpg, or .png). Redirects are followed, so you can use shortened URLs. The resolved URL is returned in the response. Maximum image size is 2 MB. All faces are detected, but if there are greater than 10 faces in an image, age and gender confidence scores may return scores of 0.

Example GET request

https://gateway-a.watsonplatform.net/visual-recognition/api/v3/detect_faces?api_key={api_key}&url=https://github.com/watson-developer-cloud/doc-tutorial-downloads/raw/master/visual-recognition/prez.jpg&version=2016-05-20

To quickly try out the API, copy the GET into the the URL bar of your browser, replace {api-key} with your API key from Bluemix, and press enter.

POST Request

Use POST /v3/detect_faces to upload a single image, URL, or a compressed (.zip) file of multiple images.

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
images_file multipart/form-data (Required) The image file (.jpg, or .png) or compressed (.zip) file of images to analyze. The total number of images is limited to 15. All faces are detected, but if there are greater than 10 faces in an image, age and gender confidence scores may return scores of 0.
parameters multipart/form-data A JSON file containing a string of a single URL to analyze.

Example POST request

curl -X POST -F "images_file=@prez.jpg" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/detect_faces?api_key={api-key}&version=2016-05-20"

Example parameters JSON file


{
    "url": "https://github.com/watson-developer-cloud/doc-tutorial-downloads/raw/master/visual-recognition/prez.jpg"
}
Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
images_file multipart/form-data (Required) The image file (.jpg, or .png) or compressed (.zip) file of images to analyze. The total number of images is limited to 15. All faces are detected, but if there are greater than 10 faces in an image, age and gender confidence scores may return scores of 0.
parameters multipart/form-data A JSON file containing a string of a single URL to analyze.

Example request

var watson = require('watson-developer-cloud');
var fs = require('fs');
var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

var params = {
  images_file: fs.createReadStream('./resources/obama.jpg')
};

visual_recognition.detectFaces(params,
  function(err, response) {
    if (err)
      console.log(err);
    else
      console.log(JSON.stringify(response, null, 2));
  });
Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
images_file multipart/form-data (Required) The image file (.jpg, or .png) or compressed (.zip) file of images to analyze. The total number of images is limited to 15.All faces are detected, but if there are greater than 10 faces in an image, age and gender confidence scores may return scores of 0.
parameters multipart/form-data A JSON file containing a string of a single URL to analyze.

Example request

  public static void main(String[] args) {
    VisualRecognition service = new VisualRecognition(VisualRecognition.VERSION_DATE_2016_05_19);
    service.setApiKey("");

    System.out.println("Detect faces");
    detectFaces = new detectFaces.Builder()
        .images(new File("src/test/resources/visual_recognition/car.png"))
        .build();
    detectFaces result = service.classify(options).execute();
    System.out.println(result);
Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
images_file multipart/form-data (Required) The image file (.jpg, or .png) or compressed (.zip) file of images to analyze. The total number of images is limited to 15.All faces are detected, but if there are greater than 10 faces in an image, age and gender confidence scores may return scores of 0.
parameters multipart/form-data A JSON file containing a string of a single URL to analyze.

Example request

import json
from os.path import join, dirname
from os import environ
from watson_developer_cloud import VisualRecognitionV3

visual_recognition = VisualRecognitionV3('2016-05-20', api_key='{api_key}')

print(json.dumps(visual_recognition.detect_faces(images_url=https://www.ibm.com/ibm/ginni/images/ginni_bio_780x981_v4_03162016.jpg), indent=2))

Response

Name Description
images The array of images.
faces An array of the faces detected in the images.
age An array of age information about a detected face. If there are greater than 10 faces in an image, age confidence scores may return a score of 0.
max The maximum estimated age for a detected face.
min The minimum estimated age for a detected face.
face_location An array of information that defines the location of bounding box around a detected face.
height Vertical distance in pixels from one edge of the bounding box around a face to the other.
left X-position of the top-left pixel of the face bounding box.
top Y-position of the top-left pixel of the face bounding box.
width Horizontal distance in pixels from one edge of the bounding box around a face to the other.
gender An array of information containing the gender of the detected face. For example, "MALE" or "FEMALE". If there are greater than 10 faces in an image, gender confidence scores may return a score of 0.
identity The identity of a celebrity detected in the image. If no celebrity is detected, the parameter returns empty.
name The name of the detected celebrity.
type_hierarchy A knowledge graph of the celebrity identity. Only return if a type hierarchy is found.
score The confidence score of the ages, gender, or celebrity indentity identified for a detected face.
image The relative path of the image file. This is omitted if the image was passed by URL.
source_url The source URL of the image, before any redirects. This is omitted if the image was uploaded.
resolved_url The fully-resolved URL of the image, after redirects are followed. This is omitted if the image was uploaded.
images_processed The number of images processed by the API call.
error An object containing information about what might have caused a failure, such as an image that is too large. This is omitted if there is no error or warning.
error_id A codified string ID for a specific error. For example, "limit_exceeded".
description A human-readable error description. For example, "File size limit (1MB) exceeded".
warnings An array containing informaton about what might cause the output to be less than optimal. For example, a call with a corrupt .zip file and a list of image URLs will still complete but will not have the expected output. This is omitted if there is no warning.

Example response

{
    "images": [
        {
            "faces": [
                {
                    "age": {
                        "max": 54,
                        "min": 45,
                        "score": 0.372036
                    },
                    "face_location": {
                        "height": 75,
                        "left": 256,
                        "top": 93,
                        "width": 67
                    },
                    "gender": {
                        "gender": "MALE",
                        "score": 0.99593
                    },
                    "identity": {
                        "name": "Barack Obama",
                        "score": 0.989013,
                        "type_hierarchy": "/people/politicians/democrats/barack
obama"
                    }
                }
            ],
            "image": "prez.jpg"
        }
    ],
    "images_processed": 1
}
}

Custom classifiers

Create a classifier

Train a new multi-faceted classifier on the uploaded image data. A new custom classifier can be trained by several compressed (.zip) files, including files containing positive or negative images (.jpg, or .png). You must supply at least two compressed files, either two positive example files or one positive and one negative example file.

Compressed files containing positive examples are used to create “classes” that define what the new classifier is. The prefix that you specify for each positive example parameter is used as the class name within the new classifier. The "_positive_examples" suffix is required. There is no limit on the number of positive example files you can upload in a single call.

The compressed file containing negative examples is not used to create a class within the created classifier, but does define what the new classifier is not. Negative example files should contain images that do not depict the subject of any of the positive examples. You can only specify one negative example file in a single call. For more information, see Structure of the training data, and Guidelines for good training.


POST /v3/classifiers

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
{classname}_positive_examples multipart/form-data (Required) A compressed (.zip) file of images that depict the visual subject for a class within the new classifier. Must contain a minimum of 10 images. Minimum recommend size is 32X32 pixels.
negative_examples multipart/form-data A compressed (.zip) file of images that do not depict the visual subject of any of the classes of the new classifier. Must contain a minimum of 10 images.
name multipart/form-data (Required) The name of the new classifier. Cannot contain spaces or special characters.

Example request

curl -X POST -F "beagle_positive_examples=@beagle.zip" -F "dalmation_positive_examples=@dalmation.zip" -F "husky_positive_example=@husky.zip" -F "negative_examples=@cats.zip" -F "name=dogs" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classifiers?api_key={api-key}&version=2016-05-20"

Depending on this size of the training files, this call can take several minutes to complete.

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

var params = {
	name: 'fruit',
	apple_positive_examples: fs.createReadStream('./apples.zip'),
    banana_positive_examples: fs.createReadStream('./yellow.zip'),
    orange_positive_examples: fs.createReadStream('./pos_ex.zip'),
	negative_examples: fs.createReadStream('./vegetables.zip')
};

visual_recognition.createClassifier(params,
	function(err, response) {
   	 if (err)
      		console.log(err);
    	 else
   		console.log(JSON.stringify(response, null, 2));
});
  public ServiceCall createClassifier(CreateClassifierOptions options) {
    Validator.notNull(options, " options cannot be null");

    Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
    bodyBuilder.addFormDataPart(PARAM_NAME, options.classifierName());

    // Classes
    for (String className : options.classNames()) {
      String dataName = className + "_" + PARAM_POSITIVE_EXAMPLES;
      RequestBody requestBody =
          RequestBody.create(HttpMediaType.BINARY_FILE, options.positiveExamplesByClassName(className));
      bodyBuilder.addFormDataPart(dataName, options.positiveExamplesByClassName(className).getName(), requestBody);
    }

    if (options.negativeExamples() != null) {
      RequestBody requestBody = RequestBody.create(HttpMediaType.BINARY_FILE, options.negativeExamples());
      bodyBuilder.addFormDataPart(PARAM_NEGATIVE_EXAMPLES, options.negativeExamples().getName(), requestBody);
    }

    RequestBuilder requestBuilder = RequestBuilder.post(PATH_CLASSIFIERS);
    requestBuilder.query(VERSION, versionDate).body(bodyBuilder.build());

    return createServiceCall(requestBuilder.build(), ResponseConverterUtils.getObject(VisualClassifier.class));
  }
with open(join(dirname(__file__), '../resources/trucks.zip'), 'rb') as trucks, \
      open(join(dirname(__file__), '../resources/cars.zip'), 'rb') as cars:
   print(json.dumps(visual_recognition.create_classifier('CarsvsTrucks', trucks_positive_examples=trucks, negative_examples=cars), indent=2))

Response

Name Description
classifier_id The ID of the new classifier.
name The name of the new classifier.
owner Unique ID of the account who owns the classifier.
status The training status of the new classifier.
explanation Omitted if the classifier trains successfully. If the classifier training fails, this might explain why training failed.
created The time and date when classifier was created.
classes An array of classes that define a classifier.
class The name of the class.

Example response

{
    "classifier_id": "{classifier_id}",
    "name": "dogs",
    "owner": "{api-key}",
    "status": "unavailable",
    "created": "2016-05-04T21:49:16.908Z",
    "classes": [
        {"class": "dalmation"},
        {"class": "beagle"},
        {"class": "husky"}
    ]
}

Retrieve a list of custom classifiers

Retrieve a list of user-created classifiers.


GET /v3/classifiers

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
verbose query Specify true to return classifier details. Omit this parameter to return a brief list of classifiers.

Example request

curl -X GET "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classifiers?api_key={api-key}&version=2016-05-20"
var watson = require('watson-developer-cloud');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

visual_recognition.listClassifiers({},
	function(err, response) {
	 if (err)
		console.log(err);
	 else
		console.log(JSON.stringify(response, null, 2));
	}
);
  public ServiceCall> getClassifiers() {
    RequestBuilder requestBuilder =
        RequestBuilder.get(PATH_CLASSIFIERS).query(VERSION, versionDate).query(VERBOSE, true);

    ResponseConverter> converter =
        ResponseConverterUtils.getGenericObject(TYPE_LIST_CLASSIFIERS, PARAM_CLASSIFIERS);
    return createServiceCall(requestBuilder.build(), converter);
  }
print(json.dumps(visual_recognition.list_classifiers(), indent=2))

Response

Name Description
classifiers The array of classifier names.
classifier_id The ID of the classifier.
name The name of the classifier.
status The training status of classifier.
owner Unique ID of the account who owns the classifier. Returned only when verbose=true.
created The time and date when classifier was created. Returned only when verbose=true.

Example response

{"classifiers": [
    {
        "classifier_id": "dogs_1712183938",
        "name": "dogs",
        "status": "ready"
    },
    {
        "classifier_id": "my_classifier_1050835757",
        "name": "my classifier",
        "status": "ready"
    }
]}

Retrieve classifier details

Retrieve information about a specific classifier.


GET /v3/classifiers/{classifier_id}

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
classifier_id path Required. The ID of the classifier for which you want details.

Example request

curl -X GET
"https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classifiers/{your-classifier}?api_key={api-key}&version=2016-05-20" 
var watson = require('watson-developer-cloud');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

visual_recognition.getClassifier({
	classifier_id: '{classifier_id}' },
	function(err, response) {
	 if (err)
		console.log(err);
	 else
		console.log(JSON.stringify(response, null, 2));
	}
);
  public ServiceCall getClassifier(String classifierId) {
    Validator.isTrue(classifierId != null && !classifierId.isEmpty(), "classifierId cannot be null or empty");

    RequestBuilder requestBuilder = RequestBuilder.get(String.format(PATH_CLASSIFIER, classifierId));
    requestBuilder.query(VERSION, versionDate);
    return createServiceCall(requestBuilder.build(), ResponseConverterUtils.getObject(VisualClassifier.class));
  }
print(json.dumps(visual_recognition.get_classifier('YOUR CLASSIFIER ID'), indent=2))

Response

Name Description
classifier_id The ID of the specified classifier.
name The name of the specified classifier.
owner Unique ID of the account who owns the classifier.
status The training status of classifier.
created The time and date when classifier was created.
classes An array of classes that define a classifier.
class The name of the class.

Example response

{
    "classifier_id": "fruits_1050835757",
    "name": "fruits",
    "owner": "{api-key}",
    "status": "ready",
    "created": "2016-05-06T21:13:19.426Z",
    "classes": [
        {"class": "apple"},
        {"class": "banana"},
        {"class": "orange"}
    ]
}

Update a classifier

Update an existing classifier by adding new classes, or by adding new images to existing classes. You cannot update a custom classifier with a free API Key.

To update the existing classifier, use several compressed (.zip) files, including files containing positive or negative images (.jpg, or .png). You must supply at least one compressed file, with additional positive or negative examples.

Compressed files containing positive examples are used to create and update “classes” to impact all of the classes in that classifier. The prefix that you specify for each positive example parameter is used as the class name within the new classifier. The "_positive_examples" suffix is required. There is no limit on the number of positive example files you can upload in a single call.

The compressed file containing negative examples is not used to create a class within the created classifier, but does define what the updated classifier is not. Negative example files should contain images that do not depict the subject of any of the positive examples. You can only specify one negative example file in a single call. For more information, see Updating custom classifiersIf you submit retraining requests in parallel, the last request overwrites all previous requests.


POST /v3/classifiers/{classifier_id}

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
{classname}_positive_examples multipart/form-data (Required) A compressed (.zip) file of images that depict the visual subject for a class within the new classifier. Suggest a minimum of 10 images. Minimum recommend size is 32X32 pixels.
negative_examples multipart/form-data A compressed (.zip) file of images that do not depict the visual subject of any of the classes of the new classifier. Suggest a minimum of 10 images.
classifier_id Path (Required) The ID of the classifier that you want to update. To see a list of classifiers, use the GET /v3/classifiers method.

Example request

curl -X POST -F "golden_positive_examples=@golden-retriever.zip" -F "negative_examples=@more-cats.zip" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classifiers/{classifier_id}?api_key={api-key}&version=2016-05-20" 

Depending on this size of the training files, this call can take several minutes to complete.

Replace {classifier_id} with the ID of the classifier that you want to update.

Replace {api-key} with your API key.

Node.js example coming soon.
var watson = require('watson-developer-cloud'); var fs = require('fs'); var visual_recognition = watson.visual_recognition({ api_key: '{api_key}', version: 'v3', version_date: '2016-05-20' }); var params = { name: 'fruit', apple_positive_examples: fs.createReadStream('./apples.zip'), banana_positive_examples: fs.createReadStream('./yellow.zip'), orange_positive_examples: fs.createReadStream('./pos_ex.zip'), negative_examples: fs.createReadStream('./vegetables.zip') }; visual_recognition.createClassifier(params, function(err, response) { if (err) console.log(err); else console.log(JSON.stringify(response, null, 2)); });
Java example coming soon.
Python example coming soon.

Response

Name Description
classifier_id The ID of the new classifier.
name The name of the new classifier.
owner Unique ID of the account who owns the classifier.
status The training status of the new classifier.
explanation Omitted if the classifier trains successfully. If the classifier training fails, this might explain why training failed.
created The time and date when classifier was created.
classes An array of classes that define a classifier.
class The name of the class.

Example response

{
    "classifier_id": "dogs_960559343",
    "name": "dogs",
    "owner": "{api-key}",
    "status": "unavailable",
    "created": "2016-05-04T21:49:16.908Z",
    "classes": [
        {"class": "golden"}
    ]
}

Delete a classifier

Delete a custom classifier with the specified classifier ID.

DELETE /v3/classifiers/{classifier_id}

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
classifier_id path (Required) The ID of the classifier you want to delete.

Example request

curl -X DELETE
"https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classifiers/{classifier_id}?api_key={api-key}&version=2016-05-20"

Replace {classifier_id} with the ID of the classifier that you want to update.

Replace {api-key} with your API key.


var watson = require('watson-developer-cloud');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

visual_recognition.deleteClassifier({
	classifier_id: 'tiger_1234' },
	function(err, response) {
	 if (err)
		console.log(err);
	 else
		console.log(JSON.stringify(response, null, 2));
	}
);
  public ServiceCall<Void> deleteClassifier(String classifierId) {
    Validator.isTrue(classifierId != null && !classifierId.isEmpty(), "classifierId cannot be null or empty");

    RequestBuilder requestBuilder = RequestBuilder.delete(String.format(PATH_CLASSIFIER, classifierId));
    requestBuilder.query(VERSION, versionDate);
    return createServiceCall(requestBuilder.build(), ResponseConverterUtils.getVoid());
  }
print(json.dumps(visual_recognition.delete_classifier(classifier_id='YOUR CLASSIFIER ID'), indent=2))

Response

No arguments

Example response

{ }

Collections - BETA

Beta. Create a new collection, add images to that collection, and then use Similarity Search to search the collection for similar images.

Create a collection

Beta. Create a new collection of images to search. You can create a maximum of 5 collections.

POST /v3/collections

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
name multipart/form-data (Required) The name of the new collection. The name can be a maximum of 128 UTF8 characters, with no spaces.

Example request

curl -X POST -F "name=dresses" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections?api_key={api-key}&version=2016-05-20"

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-20'
});

var params = {
	name: 'dresses'
};

visual_recognition.createCollection(params,
	function(err, response) {
   	 if (err)
      		console.log(err);
    	 else
   		console.log(JSON.stringify(response, null, 2));
});
Java example coming soon.
Python code example coming soon.

Response

Name Description
collection_id The ID of the new collection.
name The name of the new collection.
created The date the collection was created.
images The number of images in the collection.
status The status of collection creation. Returns available when the collection is available to add images, and unavailable when the collection is being created or trained.
capacity The number of images possible in the collection. Each collection can contain 1000000 images.

Example response

{
"collection_id": "dresses_1257263",
"name": "dresses",
"created": "2016-09-04T21:49:16.908Z",
"images": "0",
"status": "available",
"capacity": 1000000
}

List collections

Beta. List all custom collections.

GET /v3/collections

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.

Example request

curl -X GET "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections?api_key={api-key}&version=2016-05-20"

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

visual_recognition.listCollections({},
	function(err, response) {
	 if (err)
		console.log(err);
	 else
		console.log(JSON.stringify(response, null, 2));
	}
);
Java example coming soon.
Python code example coming soon.

Response

Name Description
collections Lists all collections you've created.
collection_id The ID of the new collection.
name The name of the new collection.
created The date the collection was created.
images The number of images in the collection.
status The status of collection creation. Returns available when the collection is available to add images, and unavailable when the collection is being created or trained.
capacity The number of images possible in the collection. Each collection can contain 1000000 images.

Example response

{  
   "collections":[  
      {  
         "collection_id":"dresses_1257263",
         "name":"dresses",
         "created":"2016-09-04T21:49:16.908Z",
         "images":"0",
         "status":"Available",
         "capacity": 1000000
      }
   ]
}

Retrieve collection details

Beta. Retrieve information about a specific collection.

GET /v3/collections/{collection_id}

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
collection_id path (Required) The ID of your collection.

Example request

curl -X GET "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections/{collection_id}?api_key={api-key}&version=2016-05-20"

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

visual_recognition.getCollection({
	collection_id: '{collection_id}' },
	function(err, response) {
	 if (err)
		console.log(err);
	 else
		console.log(JSON.stringify(response, null, 2));
	}
);
Java example coming soon.
Python code example coming soon.

Response

Name Description
collection_id The ID of the new collection.
name The name of the new collection.
created The date the collection was created.
images The number of images in the collection.
status The status of collection creation. Returns available when the collection is available to add images, and unavailable when the collection is being created or trained.
capacity The number of images possible in the collection. Each collection can contain 1000000 images.

Example response

{
"collection_id": "dresses_1257263",
"name": "dresses",
"created": "2016-09-04T21:49:16.908Z",
"images": "0",
"status": "available",
"capacity": 1000000
}

Delete a collection

Beta. Delete a user created collection.

DELETE /v3/collections/{collection_id}

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
collection_id path (Required) The ID of your collection.

Example request

curl -X DELETE "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections/{collection_id}?api_key={api-key}&version=2016-05-20"

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

visual_recognition.deleteCollection({
	collection_id: '{collection_id}'},
	function(err, response) {
	 if (err)
		console.log(err);
	 else
		console.log(JSON.stringify(response, null, 2));
	}
);
Java example coming soon.
Python code example coming soon.

Response

No arguments

Example response

{ }

Add images to a collection

Beta. Add images to a collection. Each collection can contain 1000000 images. It takes 1 second to upload 1 images, so uploading 1000000 images takes 11 days.

POST /v3/collections/{collection_id}/images

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
collection_id path (Required) The ID of your collection.
image_file multipart/form-data (Required) The image file (.jpg or .png) of the image to add to the collection. Maximum file size of 2 MB. There’s no recommended resolution for images. If you don’t need images of a specific resolution for your use case, shrinking images makes requests faster. Minimum recommend size is 32X32 pixels. While it is possible to upload several images at the same time, these concurrent requests are not supported. It is also not possible to upload more than one image at a time using a single request (for example, by uploading a .zip file, or a folder of images).
metadata multipart/form-data A json object file that adds metadata to the image. This can be anything that can be specified in a JSON object. For example, key-value pairs. Maximum 2 KB of metadata for each image. Use metadata for your own reference to identify images.

Example request

curl -X POST -F "image_file=@silver-dress.jpg" -F "metadata=@silver-dress.json" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections/{collection_id}/images?api_key={api-key}&version=2016-05-20"

Example JSON metadata file

{  
   "weight":10,
   "cut":"a line",
   "color":"red"
}

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

var params = {
	collection_id: '{collection_id}',
    image_file: fs.createReadStream('silver-dress.jpg'),
    metadata: { foo: 'bar' }
};

visual_recognition.addImage(params,
	function(err, response) {
   	 if (err)
      		console.log(err);
    	 else
   		console.log(JSON.stringify(response, null, 2));
});
Java example coming soon.
Python code example coming soon.

Response

Name Description
images The list of images in the collection.
image_id The ID of the image.
created The date the image was added to the collection.
image_file The file name of the image listed.
metadata Any metadata you associate with the image.
images_processed The number of images processed in the request.

Example response

{  
   "images":[  
      {  
         "image_id":"565838654",
         "created":"2016-09-04T21:49:16.908Z",
         "image_file":"red-dress.jpg",
         "metadata":{  
            "weight":10,
            "cut":"a line",
            "color":"red"
         },
         "images_processed": 1 
      }

List images in a collection

Beta. List 100 images in a collection. This returns an arbitrary selection of 100 images. Each collection can contain 1000000 images.

GET /v3/collections/{collection_id}/images

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
collection_id path (Required) The ID of your collection.

Example request

curl -X GET "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections/{collection_id}/images?api_key={api-key}&version=2016-05-20"

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

var params = {
	collection_id: '{collection_id}',
};

visual_recognition.listImages(params,
	function(err, response) {
   	 if (err)
      		console.log(err);
    	 else
   		console.log(JSON.stringify(response, null, 2));
});
Java example coming soon.
Python code example coming soon.

Response

Name Description
images The list of images in the collection.
image_id The ID of the image.
created The date the image was added to the collection.
image_file The file name of the image listed.
metadata Any metadata you associate with the image.

Example response

{  
   "images":[  
      {  
         "image_id":"565838654",
         "created":"2016-09-04T21:49:16.908Z",
         "image_file":"red_dress.jpg",
         "metadata":{  
            "weight":10,
            "cut":"a line",
            "color":"red"
         }
      }
   ]

List image details

Beta. List details about a specific image in a collection.

GET /v3/collections/{collection_id}/images/{image_id}

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
collection_id path (Required) The ID of your collection.
image_id path (Required) The ID of your image.

Example request

curl -X GET "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections/{collection_id}/images/{image_id}?api_key={api-key}&version=2016-05-20"

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

var params = {
	collection_id: '{collection_id}',
    image_id: '{image_id}'
};

visual_recognition.getImage(params,
	function(err, response) {
   	 if (err)
      		console.log(err);
    	 else
   		console.log(JSON.stringify(response, null, 2));
});
Java example coming soon.
Python code example coming soon.

Response

Name Description
image_id The ID of the image.
created The date the image was added to the collection.
image_file The file name of the image listed.
metadata Any metadata you associate with the image.

Example response

{  
   "image_id":"565838654",
   "created":"2016-09-04T21:49:16.908Z",
   "image_file":"red_dress.jpg",
   "metadata":{  
      "weight":10,
      "cut":"a line",
      "color":"red"
   }
}

Delete an image

Beta. Delete an image from a collection.

DELETE /v3/collections/{collection_id}/images/{image_id}

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
collection_id path (Required) The ID of your collection.
image_id path (Required) The ID of your image.

Example request

curl -X DELETE "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections/{collection_id}/images/{image_id}?api_key={api-key}&version=2016-05-20"

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

var params = {
	collection_id: '{collection_id}',
    image_id: '{image_id}'
};

visual_recognition.deleteImage(params,
	function(err, response) {
   	 if (err)
      		console.log(err);
    	 else
   		console.log(JSON.stringify(response, null, 2));
});
Java example coming soon.
Python code example coming soon.

Response

No arguments

Example response

{ }

Add or update metadata

Beta. Add metadata to a specific image in a collection. Use metadata for your own reference to identify images. You cannot filter the find_similar method by metadata.

PUT /v3/collections/{collection_id}/images/{image_id}/metadata

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
collection_id path (Required) The ID of your collection.
image_id path (Required) The ID of your image.
metadata multipart/form-data (Required) A json object file that adds metadata to the image. This can be anything that can be specified in a JSON object. For example, key-value pairs. Maximum 2 KB of metadata for each image.

Example request

curl -X PUT -F "metadata=@red_dress.json" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections/{collection_id}/images/{image_id}/metadata?api_key={api-key}&version=2016-05-20"

Example JSON metadata file

{  
   "weight":10,
   "cut":"a line",
   "color":"red"
}

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

var params = {
	collection_id: '{collection_id}',
    image_id: '{image_id}',
    metadata: { meta: 'data' }
};

visual_recognition.setImageMetadata(params,
	function(err, response) {
   	 if (err)
      		console.log(err);
    	 else
   		console.log(JSON.stringify(response, null, 2));
});
Java example coming soon.
Python code example coming soon.

Response

Name Description
metadata Whatever you specify for the metadata object.

Example response

{  
   "weight":10,
   "cut":"a line",
   "color":"red"
}

List metadata

Beta. View the metadata for a specific image in a collection.

GET /v3/collections/{collection_id}/images/{image_id}/metadata

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
collection_id path (Required) The ID of your collection.
image_id path (Required) The ID of your image.

Example request

curl -X GET "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections/{collection_id}/images/{image_id}/metadata?api_key={api-key}&version=2016-05-20"

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

var params = {
	collection_id: '{collection_id}',
    image_id: '{image_id}'
};

visual_recognition.getImageMetadata(params,
	function(err, response) {
   	 if (err)
      		console.log(err);
    	 else
   		console.log(JSON.stringify(response, null, 2));
});
Java example coming soon.
Python code example coming soon.

Response

Name Description
metadata Whatever metadata is associated with the image.

Example response

{  
   "weight":10,
   "cut":"a line",
   "color":"red"
}

Delete metadata

Beta. Delete all metadata associated with an image.

DELETE /v3/collections/{collection_id}/images/{image_id}/metadata

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
collection_id path (Required) The ID of your collection.
image_id path (Required) The ID of your image.

Example request

curl -X DELETE "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections/{collection_id}/images/{image_id}/metadata?api_key={api-key}&version=2016-05-20"

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

var params = {
	collection_id: '{collection_id}',
    image_id: '{image_id}'
};

visual_recognition.deleteImageMetadata(params,
	function(err, response) {
   	 if (err)
      		console.log(err);
    	 else
   		console.log(JSON.stringify(response, null, 2));
});
Java example coming soon.
Python code example coming soon.

Response

No arguments

Example response

{ }

Find similar images

Beta. Upload an image to find similar images in your custom collection.

POST /v3/collections/{collection_id}/find_similar

Request

Parameter Type Description
api_key query (Required) Your API key.
version query (Required) The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2016-05-20.
collection_id path (Required) The ID of your collection.
image_file multipart/form-data (Required) The image file (.jpg or .png) of the image to search against the collection. Minimum recommend size is 32X32 pixels.
limit query The number of similar results you want returned. Default limit is 10 results, you can specify a maximum limit of 100 results.

Example request

curl -X POST -F "image_file=@silver_dress2.jpg" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/collections/{collection_id}/find_similar?limit=100&api_key={api-key}&version=2016-05-20"

var watson = require('watson-developer-cloud');
var fs = require('fs');

var visual_recognition = watson.visual_recognition({
  api_key: '{api_key}',
  version: 'v3',
  version_date: '2016-05-19'
});

var params = {
	collection_id: '{collection_id}',
    image_file: fs.createReadStream('silver_dress2.jpg')
};

visual_recognition.findSimilar(params,
	function(err, response) {
   	 if (err)
      		console.log(err);
    	 else
   		console.log(JSON.stringify(response, null, 2));
});
Java example coming soon.
Python code example coming soon.

Response

Name Description
similar_images The list of similar images.
image_id The ID of the image.
created The date the image was added to the collection.
image_file The file name of the image listed.
metadata Any metadata you associate with the image.
score Confidence in the similarity.
images_processed Number of images processed in this call.

Example response

{
  "image_file": "red-dress.jpg",
  "similar_images": [
    {
      "image_id": "55e39b",
      "image_file": "red-dress.jpg",
      "score": 1,
      "created": "2016-09-13T20:05:42.951Z",
      "metadata": {
        "key": "value"
      }
    },
    {
      "image_id": "1e657a",
      "image_file": "blue-dress.jpg",
      "score": 0.60839844,
      "created": "2016-09-13T20:05:22.049Z",
      "metadata": {
        "key": "value"
      }
    },
    {
      "image_id": "88b900",
      "image_file": "purple-dress.jpg",
      "score": 0.57666016,
      "created": "2016-09-13T20:05:35.323Z",
      "metadata": {
        "key": "value"
      }
    }
  ],
  "images_processed": 1
}

Data collection

By default, Bluemix collects data from all requests and uses the data to improve the services. If you do not want to share your data, set a header parameter X-Watson-Learning-Opt-Out with the value true for all requests. If you do not specify this header in all payload data, data is collected and used to improve the service.

Error handling

The Visual Recognition service uses standard HTTP response codes to display whether a method completed successfully. A 200 response always indicates success. A 400 type response is some sort of failure, and a 500 type response usually indicates an internal system error.

Error information

Status Description
200 - Partial Success Problems with an individual image in an otherwise successfull request, for example, an image of invalid type
400 - Invalid Request Invalid request due to user input, for example:
  • Bad JSON input
  • Bad query parameter or header
  • No input images given
  • Total POST size greater than 5 MB
  • Corrupt .zip file
401 - Unauthorized No API key provided, or the API key provided was not valid.
404 - Not Found The requested item or parameter doesn't exist.
500 - Internal Server Error Too many training requests or general server communication problems

Error format

Name Description
error An object containing information about the error.
code HTTP status code

Example error response

   {
      "error": "Too many images in collection",
      "code": 400
   }

Attributions

All images used on this page are from Flikr and used under Creative Commons Attribution 2.0 license . No changes were made to these images.