vision
Ask a local vision model about an image: which objects are where, which booru tags describe it, a caption, or embeddings that say how parts of it look. The model must be running: start it with agency local serve <model>. The image never leaves the machine.
import { detectObjects, tagImage } from "std::vision"
import { cropImage } from "std::image"
node main() {
handle {
const found = detectObjects("page.png", ["person", "desk", "chair"], "florence-2") catch []
for (hit in found) {
cropImage("page.png", hit.box, "crops/${hit.label}_${hit.id}.png", pad: 0.05)
}
const tags = tagImage("crops/person_0.png", "wd14-tagger") catch []
const names = map(tags) as t {
return t.tag
}
print(names.join(", "))
} with approve
}Each function is one job with a Result, so a labeling loop is a few lines of your own code over them, and partial application narrows each: detectObjects.partial(labels: ["person"], model: "florence-2") is a person-finder.
Finding your own things
A detector finds things by the name of their kind. It finds every mug, and cannot tell yours from the one next to it. To find your own mug, or the cats you draw, compare instead:
findRegionsboxes every thing in a picture, with no names. Where a detector knows the kind,detectObjectsgives the boxes instead.embedImageturns each box into an embedding: a list of numbers that says how it looks. Things that look alike get embeddings that are close together.- Compare each box with embeddings of crops of your own things, and of other things, and keep the boxes nearest yours.
import { findRegions, embedImage } from "std::vision"
import { cosineSimilarity } from "std::embedding"
// How alike `vector` is to the closest of `references`, where 1 is identical.
def closest(vector: number[], references: number[][]): number {
let best = 0
for (reference in references) {
const similarity = cosineSimilarity(vector, reference)
if (isSuccess(similarity) && similarity.value > best) {
best = similarity.value
}
}
return best
}
// One vector per crop file.
def embedCrops(paths: string[]): number[][] {
let vectors: number[][] = []
for (path in paths) {
const embedded = embedImage(path, "dinov2-base")
if (isSuccess(embedded)) {
vectors.push(embedded.value[0])
}
}
return vectors
}
node main(page: string, catCrops: string[], otherCrops: string[]) {
const cats = embedCrops(catCrops)
const others = embedCrops(otherCrops)
const regions = findRegions(page, "owlv2-base")
if (isFailure(regions)) {
return regions.error
}
const boxes = map(regions.value) as region {
return region.box
}
const vectors = embedImage(page, "dinov2-base", boxes: boxes)
if (isFailure(vectors)) {
return vectors.error
}
for (vector, i in vectors.value) {
if (closest(vector, cats) > closest(vector, others)) {
print("Cat in region ${i}")
}
}
}The crops are tight crops made with cropImage, one file each. A crop file embedded whole is cut the same way as a box embedded from a page, so the two compare fairly. A whole photo of a mug on a desk and a tight crop of a mug do not: the first vector mostly describes the desk.
Types
BoundingBox
Normalized to 0..1 with the origin at the top left of the image, so y grows downward. The same shape std::ocr returns, so a box from either can go to cropImage.
/** Normalized to 0..1 with the origin at the top left of the image, so
`y` grows downward. The same shape std::ocr returns, so a box from
either can go to cropImage. */
export type BoundingBox = {
x: number;
y: number;
width: number;
height: number
}(source)
Detection
One thing a detector found. id is its index in the reply, so crops can be named after it. The box is normalized 0..1 from the top left.
/** One thing a detector found. `id` is its index in the reply, so crops
can be named after it. The box is normalized 0..1 from the top left. */
export type Detection = {
id: number;
label: string;
score: number;
box: BoundingBox
}(source)
Region
One box around a thing in a picture, found with no name. id is its index in the reply, so crops can be named after it. The score says how much it looks like a thing at all, 0..1.
/** One box around a thing in a picture, found with no name. `id` is its
index in the reply, so crops can be named after it. The score says how
much it looks like a thing at all, 0..1. */
export type Region = {
id: number;
score: number;
box: BoundingBox
}(source)
Tag
One tag a tagger gave, with how sure it was, 0..1.
/** One tag a tagger gave, with how sure it was, 0..1. */
export type Tag = {
tag: string;
score: number
}(source)
Effects
std::vision
@alwaysUnder(dir)
effect std::vision {
dir: string;
filename: string;
task: string;
model: string
}(source)
Functions
detectObjects
detectObjects(
path: string,
labels: string[],
model: string,
threshold: number | null = null,
): Result<Detection[]> raises <std::vision>Locate named objects in an image using a local detector.
Use labels for object categories such as "person" or "chair". OWLv2 handles the labels in one pass. Florence-2 makes a separate pass for each label. Florence-2 assigns every detection a score of 1. OWLv2 uses a default threshold of 0.1 when none is supplied.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| path | string | Path to a PNG, JPEG, WebP, or GIF image. | |
| labels | string[] | One to 50 object names to look for, such as "person" or "chair". | |
| model | string | A running local detector, such as "owlv2-base" or "florence-2". | |
| threshold | number | null | null | Minimum score from 0 to 1, or null for the model default. |
Returns: Result<Detection[]>
Throws: std::vision
Needs: fileRead, network
(source)
tagImage
tagImage(
path: string,
model: string,
threshold: number = 0.35,
limit: number = 30,
): Result<Tag[]> raises <std::vision>Describe an image with booru tags using a local model.
Use the returned booru tags in illustration-model prompts or caption files. Tags arrive in descending score order.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| path | string | Path to a PNG, JPEG, WebP, or GIF image. | |
| model | string | A running local tagger, such as "wd14-tagger" or "florence-2". | |
| threshold | number | 0.35 | Minimum tag score from 0 to 1. |
| limit | number | 30 | Maximum tags to return, from 1 to 500. |
Returns: Result<Tag[]>
Throws: std::vision
Needs: fileRead, network
(source)
captionImage
captionImage(
path: string,
model: string,
detail: string = "short",
): Result<string> raises <std::vision>Write a sentence about an image with a local model. Runs on this machine; nothing is uploaded.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| path | string | Path to a PNG, JPEG, WebP, or GIF image | |
| model | string | A local vision model that captions, such as "florence-2" | |
| detail | string | "short" | "short" for one sentence, "long" for a paragraph |
Returns: Result<string>
Throws: std::vision
Needs: fileRead, network
(source)
embedImage
embedImage(
path: string,
model: string,
boxes: BoundingBox[] | null = null,
): Result<number[][]> raises <std::vision>Embed a whole image or selected regions for visual similarity comparisons. Compare vectors from the same model and with similar crop framing.
Compare vectors with cosineSimilarity from std::embedding. Use crops from the same model and with similar framing. Compare against labeled examples of both the objects you want and other objects; the module example shows how to choose the closer group.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| path | string | Path to a PNG, JPEG, WebP, or GIF image. | |
| model | string | A running local embedding model, such as "dinov2-base". | |
| boxes | BoundingBox[] | null | null | Up to 100 normalized regions, or null for the whole image. |
Returns: Result<number[][]>
Throws: std::vision
Needs: fileRead, network
(source)
findRegions
findRegions(
path: string,
model: string,
limit: number = 50,
threshold: number | null = null,
): Result<Region[]> raises <std::vision>Find candidate object regions in an image using a local model, without labels.
Use this before embedImage when you want candidate objects without choosing category names. Regions arrive in descending score order. Florence-2 gives every region a score of 1; OWLv2 defaults to a threshold of 0.1.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| path | string | Path to a PNG, JPEG, WebP, or GIF image. | |
| model | string | A running local region model, such as "owlv2-base" or "florence-2". | |
| limit | number | 50 | Maximum regions to return, from 1 to 100. |
| threshold | number | null | null | Minimum score from 0 to 1, or null for the model default. |
Returns: Result<Region[]>
Throws: std::vision
Needs: fileRead, network
(source)