Roboflow Docs
DashboardResourcesProducts
  • Product Documentation
  • Developer Reference
  • Changelog
  • Roboflow Documentation
  • Quickstart
  • Workspaces
    • Workspaces, Projects, and Models
    • Create a Workspace
    • Rename a Workspace
    • Delete a Workspace
  • Team Members
    • Invite a Team Member
    • Role-Based Access Control (RBAC)
    • Change a Team Member Role
    • Remove a Team Member
  • Single Sign On (SSO)
  • Workflows
    • What is Workflows?
    • Create a Workflow
    • Build a Workflow
    • Test a Workflow
    • Deploy a Workflow
    • Workflow Examples
      • Multimodal Model Workflow
    • Share a Workflow
    • Workflows AI Assistant
  • Enterprise Integrations
  • Workflow Blocks
    • Run a Model
      • Object Detection Model
      • Single-Label Classification Model
    • Visualize Predictions
      • Bounding Box Visualization
      • Label Visualization
      • Circle Visualization
      • Background Color Visualization
      • Classification Label Visualization
      • Crop Visualization
  • Dataset Management
    • Create a Project
    • Upload Images, Videos, and Annotations
      • Import Data from Cloud Providers
        • AWS S3 Bucket
        • Azure Blob Storage
        • Google Cloud Storage
      • Import from Roboflow Universe
    • Manage Datasets
      • Dataset Batches
      • Search a Dataset
      • Set Dataset Classes
      • Add Tags to Images
      • Create an Annotation Attribute
      • Download an Image
      • Delete an Image
    • Dataset Versions
      • Create a Dataset Version
      • Preprocess Images
      • Augment Images
      • Delete a Version
    • Dataset Analytics
    • Merge Projects
    • Rename a Project
    • Delete a Project
    • Project Folders
    • Make a Project Public
    • Download a Dataset
  • Annotate
    • Introduction to Roboflow Annotate
    • Annotate an Image
      • Keyboard Shortcuts
      • Comment on an Image
      • Annotation History
      • Similarity Search
    • AI Labeling
      • Label Assist
      • Enhanced Smart Polygon with SAM
        • Smart Polygon (Legacy)
      • Box Prompting
      • Auto Label
    • Set Keypoint Skeletons
    • Annotate Keypoints
    • Annotate Multimodal Data
    • Collaborate on Labeling
    • Annotation Insights
  • Managed Labeling
  • Train
    • Train a Model
      • Train from a Universe Checkpoint
      • Train from Azure Vision
      • Train from Google Cloud
    • Roboflow Instant
    • Cancel a Training Job
    • Stop Training Early
    • View Training Results
    • View Trained Models
    • Evaluate Trained Models
  • Deploy
    • Deploy a Model or Workflow
    • Supported Models
    • Managed Deployments
    • Serverless Hosted API V2
      • Use in a Workflow
      • Use with the REST API
      • Run an Instant Model
    • Serverless Hosted API
      • Object Detection
      • Classification
      • Instance Segmentation
        • Semantic Segmentation
      • Keypoint Detection
      • Foundation Models
        • CLIP
        • OCR
        • YOLO-World
      • Video Inference
        • Use a Fine-Tuned Model
        • Use CLIP
        • Use Gaze Detection
        • API Reference
        • Video Inference JSON Output Format
      • Pre-Trained Model APIs
        • Blur People API
        • OCR API
        • Logistics API
        • Image Tagging API
        • People Detection API
        • Fish Detection API
        • Bird Detection API
        • PPE Detection API
        • Barcode Detection API
        • License Plate Detection API
        • Ceramic Defect Detection API
        • Metal Defect Detection API
    • Dedicated Deployments
      • Create a Dedicated Deployment
      • Make Requests to a Dedicated Deployment
      • Manage Dedicated Deployments with an API
    • Batch Processing
    • SDKs
      • Python inference-sdk
      • Web Browser
        • inferencejs Reference
        • inferencejs Requirements
      • Lens Studio
        • Changelog - Lens Studio
      • Luxonis OAK
    • Upload Custom Model Weights
    • Download Model Weights
    • Enterprise Deployment
      • License Server
      • Offline Mode
      • Kubernetes
      • Docker Compose
    • Model Monitoring
      • Alerting
  • Universe
    • What is Roboflow Universe?
    • Find a Dataset on Universe
    • Explore Images in a Universe Dataset
    • Fork a Universe Dataset
    • Find a Model on Universe
    • Download a Universe Dataset
  • Set a Project Description
  • View Project Analytics
  • Support
    • Share a Workspace with Support
    • Delete Your Roboflow Account
    • Apply for Academic Credits
  • Billing
    • Premium Trial
    • Credits
      • View Credit Usage
      • Enable or Disable Flex Billing
      • Purchase Prepaid Credits
    • Plans
      • Purchase a Plan
      • Cancel a Plan
      • Update Billing Details
      • Update Payment Method
      • View Invoices
Powered by GitBook
On this page
  • Response Object Formats
  • API Reference
  • Using the Inference API

Was this helpful?

  1. Deploy
  2. Serverless Hosted API

Classification

Run inference on classification models hosted on Roboflow.

PreviousObject DetectionNextInstance Segmentation

Last updated 3 months ago

Was this helpful?

Infer on Local and Hosted Images

To install dependencies, pip install inference-sdk.

from inference_sdk import InferenceHTTPClient

CLIENT = InferenceHTTPClient(
    api_url="https://classify.roboflow.com",
    api_key="API_KEY"
)

result = CLIENT.infer(your_image.jpg, model_id="vehicle-classification-eapcd/2")

Node.js

We use to perform the POST request in this example so first run npm install axios to install the dependency.

Inferring on a Local Image

const axios = require("axios");
const fs = require("fs");

const image = fs.readFileSync("YOUR_IMAGE.jpg", {
    encoding: "base64"
});

axios({
    method: "POST",
    url: "https://classify.roboflow.com/your-model/42",
    params: {
        api_key: "YOUR_KEY"
    },
    data: image,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    }
})
.then(function(response) {
    console.log(response.data);
})
.catch(function(error) {
    console.log(error.message);
});

Uploading a Local Image Using base64

import UIKit

// Load Image and Convert to Base64
let image = UIImage(named: "your-image-path") // path to image to upload ex: image.jpg
let imageData = image?.jpegData(compressionQuality: 1)
let fileContent = imageData?.base64EncodedString()
let postData = fileContent!.data(using: .utf8)

// Initialize Inference Server Request with API_KEY, Model, and Model Version
var request = URLRequest(url: URL(string: "https://classify.roboflow.com/your-model/your-model-version?api_key=YOUR_APIKEY&name=YOUR_IMAGE.jpg")!,timeoutInterval: Double.infinity)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData

// Execute Post Request
URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
    
    // Parse Response to String
    guard let data = data else {
        print(String(describing: error))
        return
    }
    
    // Convert Response String to Dictionary
    do {
        let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
    } catch {
        print(error.localizedDescription)
    }
    
    // Print String Response
    print(String(data: data, encoding: .utf8)!)
}).resume()

Response Object Formats

Single-Label Classification

The hosted API inference route returns a JSON object containing an array of predictions. Each prediction has the following properties:

  • time = total time, in seconds, to process the image and return predictions

  • image = an object that holds information about the image width and height

    • width the height of the predicted image

    • height = the height of the predicted image

  • predictions = collection of all predicted classes and their associated confidence values for the prediction

    • class = the label of the classification

    • confidence = the model's confidence that the image contains objects of the detected classification

  • top = highest confidence predicted class

  • confidence = highest predicted confidence score

  • image_path = path of the predicted image

  • prediction_type = the model type used to perform inference, ClassificationModel in this case

// an example JSON object
{
  "time": 0.19064618100037478,
  "image": {
    "width": 210,
    "height": 113
  },
  "predictions": [
    {
      "class": "real-image",
      "confidence": 0.7149
    },
    {
      "class": "illustration",
      "confidence": 0.2851
    }
  ],
  "top": "real-image",
  "confidence": 0.7149,
  "image_path": "/cropped-images-1.jpg",
  "prediction_type": "ClassificationModel"
}

Multi-Label Classification

The hosted API inference route returns a JSON object containing an array of predictions. Each prediction has the following properties:

  • time = total time, in seconds, to process the image and return predictions

  • image = an object that holds information about the image width and height

    • width the height of the predicted image

    • height = the height of the predicted image

  • predictions = collection of all predicted classes and their associated confidence values for the prediction

    • class = the label of the classification

    • confidence = the model's confidence that the image contains objects of the detected classification

  • predicted_classes = an array that contains a list of all classifications (labels/classes) returned in model predictions

  • image_path = path of the predicted image

  • prediction_type = the model type used to perform inference, ClassificationModel in this case

// an example JSON object
{
  "time": 0.19291414400004214,
  "image": {
    "width": 113,
    "height": 210
  },
  "predictions": {
    "dent": {
      "confidence": 0.5253503322601318
    },
    "severe": {
      "confidence": 0.5804202556610107
    }
  },
  "predicted_classes": [
    "dent",
    "severe"
  ],
  "image_path": "/car-model-343.jpg",
  "prediction_type": "ClassificationModel"
}

API Reference

Using the Inference API

POST https://classify.roboflow.com/:datasetSlug/:versionNumber

You can POST a base64 encoded image directly to your model endpoint. Or you can pass a URL as the image parameter in the query string if your image is already hosted elsewhere.

Path Parameters

Name
Type
Description

datasetSlug

string

The url-safe version of the dataset name. You can find it in the web UI by looking at the URL on the main project view.

string

The version number identifying the version of your dataset.

Query Parameters

Name
Type
Description

api_key

string

Your API key (obtained via your workspace API settings page)

{
   "predictions":{
      "bird":{
         "confidence":0.5282308459281921
      },
      "cat":{
         "confidence":0.5069406032562256
      },
      "dog":{
         "confidence":0.49514248967170715
      }
   },
   "predicted_classes":[
      "bird",
      "cat"
   ]
}
{
   "message":"Forbidden"
}j
axios