Cloudflare Docs
Workers AI
Visit Workers AI on GitHub
Set theme to dark (⇧+D)

Image classification

ResNet models perform image classification - they take images as input and classify the major object in the image.

​​ Examples


import { Ai } from '@cloudflare/ai'
export interface Env {
AI: any;
}
export default {
async fetch(request: Request, env: Env) {
const res: any = await fetch("https://cataas.com/cat");
const blob = await res.arrayBuffer();
const ai = new Ai(env.AI);
const inputs = {
image: [...new Uint8Array(blob)],
};
const response = await ai.run("@cf/microsoft/resnet-50", inputs);
return new Response(JSON.stringify({ inputs: { image: [] }, response }));
}
}

$ curl https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/@cf/microsoft/resnet-50 \
-X POST \
-H "Authorization: Bearer {API_TOKEN}" \
--data-binary @orange-llama.png

Example Workers AI response


{
"inputs": { "image":[] },
"response": [
{ "label":"PERSIAN CAT" ,"score":0.4071170687675476 },
{ "label":"PEKINESE", "score":0.23444877564907074 },
{ "label":"FEATHER BOA", "score":0.22562485933303833 },
{ "label":"POMERANIAN", "score":0.033316344022750854 },
{ "label":"JAPANESE SPANIEL", "score":0.024184171110391617 }
]
}

​​ API schema

The following schema is based on JSON Schema


{
"task": "image-classification",
"tsClass": "AiImageClassification",
"jsonSchema": {
"input": {
"type": "object",
"properties": {
"image": {
"type": "string",
"format": "binary"
}
},
"required": ["image"]
},
"output": {
"type": "array",
"items": {
"type": "object",
"properties": {
"score": {
"type": "number"
},
"label": {
"type": "string"
}
}
}
}
}
}