Export¶
Exports a generated dataset to standard formats: COCO, YOLO, Pascal VOC and BOP.
Run it once after generating, on the generating path. It reads the <index>.json
labels; only datapoints with an image (a Render step) and with bboxes or instance
masks are exported (with poses for BOP). Labels of every prefix (run1_000012.json,
from generating.Compose(prefix=...)) are read, so runs merged into one folder export
together. Image ids are the datapoint indices, or, when any label has a prefix, the
position of the label sorted by prefix and index, so they stay unique. It works without Blender. COCO with masks,
bbox_from="mask" and BOP with masks or depth need numpy and OpenImageIO, which come
with Blender.
COCO, YOLO and VOC take bbox_from, which box to write:
"label"(default): theBBoxstep's boxes, around the whole object including the parts hidden behind other objects (amodal). Needs aBBoxstep."mask": the extent of the visible pixels of each instance mask (modal), the boxes most detection datasets use. Needs aSegmentationstep withper="instance"or"both"and the same classes. Fully hidden instances, and ones whose mask was not written (skip_empty), are left out.
augmentation_stats compares how often each augmentation ran over the dataset with
the probabilities of its graph, from a generating.Augmentations step, skip_stats
counts the datapoints BBox skipped by reason, and augmentation_report draws it all
on an HTML page.
coco
¶
coco(
path: str,
output: Optional[str] = None,
*,
classes: Optional[Sequence[str]] = None,
bbox_from: Literal["label", "mask"] = "label",
) -> str
Writes a COCO detection and instance segmentation JSON.
Masks are stored as uncompressed RLE from the instance masks. Instances whose mask
is empty (fully hidden), or was not written because it was empty
(Segmentation(skip_empty=True)), are skipped. Each annotation also has an
"objects" field with the object names.
COCO example in the Quick start
Visible boxes need instance masks
By default (bbox_from="label") the boxes come from the BBox step and cover
the whole object, including the parts hidden behind other objects. For boxes
of only the visible pixels, which most detection datasets use, pass
bbox_from="mask". That needs a Segmentation step with per="instance" or
per="both", with the same classes as BBox, in the generating Compose;
without instance masks the export raises.
Parameters:
-
path(str) –generating path with the
<index>.jsonlabels.//paths are relative to the .blend file when running in Blender. -
output(Optional[str], default:None) –JSON file to write. None =
<path>/coco.json. -
classes(Optional[Sequence[str]], default:None) –class names in category id order (ids start at 1). None = in order of first appearance.
-
bbox_from(Literal['label', 'mask'], default:'label') –"label"for the boxes of theBBoxstep, around the whole object including hidden parts (amodal), or"mask"for the extent of the visible pixels in the instance masks (modal, as in the COCO dataset itself), which needsSegmentationwithper="instance"or"both". With"label", an instance with a mask but noBBoxbox gets its mask's box. See the module description.
Returns:
-
str–Path of the written file.
Raises:
-
ValueError–an unknown
bbox_from,bbox_from="mask"with an instance that has no instance mask, or a class in the labels missing fromclasses.
Note
The output is tested with pycocotools: COCO loads it, every decoded mask,
area and box match the labels, and COCOeval scores the annotations against
themselves at AP 1 for bbox and segm. The masks are uncompressed RLE with
iscrowd 0, which pycocotools and Detectron2 read; a tool that expects
polygons for non-crowd objects has to convert them first.
Example
export.coco("//dataset", classes=["car", "table"])
yolo
¶
yolo(
path: str,
*,
task: Literal["detect", "segment"] = "detect",
classes: Optional[Sequence[str]] = None,
bbox_from: Literal["label", "mask"] = "label",
tolerance: float = 0.0,
) -> str
Writes YOLO labels for detection or instance segmentation.
Writes <index>.txt next to every image, classes.txt, images.txt (the list of
the dataset's images, so the masks, previews and passes in the folder aren't taken
for images) and dataset.yaml pointing at it, ready for Ultralytics. Each line of a
.txt is one object, with coordinates normalized to 0-1:
task="detect":class x_center y_center width height, its box.task="segment":class x1 y1 x2 y2 ..., the outline of its instance mask as a polygon (Ultralytics segmentation format). Ultralytics takes the box from the polygon. Needs aSegmentationstep withper="instance"or"both"; instances with no visible pixels are left out.
The two tasks write the same .txt files, so a folder holds one of them; the last
export wins.
YOLO examples in the Quick start
How a mask becomes a polygon (in numpy, Blender has no OpenCV): its points are the
centers of the pixels at the edge of the mask (as OpenCV's findContours finds them,
which Ultralytics' own mask converter uses), and a diagonal edge goes straight from
pixel to pixel. Ultralytics draws a polygon back into a mask with OpenCV's
fillPoly, which fills it and its edge pixels: that gives exactly the mask (tested
with Ultralytics' polygon2mask). tolerance simplifies the outline (Douglas-Peucker, like
OpenCV's approxPolyDP) for shorter lines, at the cost of pixels along the edge.
A row holds one polygon, so:
- an object split into pieces, e.g. by something in front of it, is one polygon:
the pieces are joined by zero-width bridges, walked there and back, as Ultralytics
joins the pieces of a COCO object (
merge_multi_segment), so the object stays one instance. Drawn back, a bridge is a line of pixels between the pieces, also as in Ultralytics; - holes in a mask are filled (an object seen through a gap, a ring), since a
polygon can't have them. COCO polygons fill them the same way;
export.cocokeeps them, its masks are run-length encoded.
Visible boxes need instance masks
By default (bbox_from="label") the boxes come from the BBox step and cover
the whole object, including the parts hidden behind other objects. For boxes
of only the visible pixels, which most detection datasets use, pass
bbox_from="mask". That needs a Segmentation step with per="instance" or
per="both", with the same classes as BBox, in the generating Compose;
without instance masks the export raises.
Parameters:
-
path(str) –generating path with the
<index>.jsonlabels. -
task(Literal['detect', 'segment'], default:'detect') –"detect"for boxes,"segment"for the polygons of the instance masks. -
classes(Optional[Sequence[str]], default:None) –class names in class id order (ids start at 0). None = in order of first appearance.
-
bbox_from(Literal['label', 'mask'], default:'label') –with
task="detect","label"for the boxes of theBBoxstep, around the whole object including hidden parts (amodal), or"mask"for the extent of the visible pixels in the instance masks (modal), which needsSegmentationwithper="instance"or"both"; fully hidden instances are left out. See the module description. Not used by"segment", whose polygons are always the visible pixels. -
tolerance(float, default:0.0) –with
task="segment", how far in pixels the simplified outline may be from the mask's edge pixels. 0 (the default) keeps the outline exact, with about as many points as Ultralytics' own converter writes; 1 has about 5 times fewer points and loses some pixels along the edges.
Returns:
-
str–Path of
dataset.yaml.
Raises:
-
ValueError–an unknown
taskorbbox_from, a negativetolerance,bbox_from="mask"ortask="segment"with an instance that has no instance mask, or a class in the labels missing fromclasses.
Note
Ultralytics finds a label by the image path with images replaced by labels,
or, when the path has no images folder, next to the image, where this writes
them. Keep images out of the dataset path, or move the .txt files to a
labels folder next to an images one.
Example
export.yolo("//dataset")
export.yolo("//dataset", bbox_from="mask") # boxes of the visible pixels
export.yolo("//dataset", task="segment") # polygons, for YOLO segmentation models
voc
¶
voc(
path: str,
output: Optional[str] = None,
*,
bbox_from: Literal["label", "mask"] = "label",
) -> str
Writes Pascal VOC XML annotations, one file per image, with 1-based pixel bboxes.
Boxes touching the image border are marked truncated.
Pascal VOC example in the Quick start
Visible boxes need instance masks
By default (bbox_from="label") the boxes come from the BBox step and cover
the whole object, including the parts hidden behind other objects. For boxes
of only the visible pixels, which most detection datasets use, pass
bbox_from="mask". That needs a Segmentation step with per="instance" or
per="both", with the same classes as BBox, in the generating Compose;
without instance masks the export raises.
Parameters:
-
path(str) –generating path with the
<index>.jsonlabels. -
output(Optional[str], default:None) –folder for the XML files. None =
<path>/Annotations. -
bbox_from(Literal['label', 'mask'], default:'label') –"label"for the boxes of theBBoxstep, around the whole object including hidden parts (amodal), or"mask"for the extent of the visible pixels in the instance masks (modal, as in Pascal VOC itself), which needsSegmentationwithper="instance"or"both"; fully hidden instances are left out. See the module description.
Returns:
-
str–The output folder.
Raises:
-
ValueError–an unknown
bbox_from, orbbox_from="mask"with an instance that has no instance mask.
Example
export.voc("//dataset")
export.voc("//dataset", bbox_from="mask") # boxes of the visible pixels
bop
¶
bop(
path: str,
output: Optional[str] = None,
*,
classes: Optional[Sequence[str]] = None,
scene_id: int = 0,
split: str = "train_pbr",
depth_scale: float = 1.0,
) -> str
Writes the dataset as one scene of a BOP dataset, for 6D pose estimation.
Writes <output>/<split>/<scene_id>/ with rgb/, scene_camera.json and
scene_gt.json; with masks also mask/, mask_visib/ and scene_gt_info.json,
and with a Depth pass depth/. <output>/camera.json gets the first image's
camera, and <output>/obj_ids.json the class name of every obj_id. Image ids
are the datapoint indices (numbered in order with prefixes), and obj_ids number the classes from 1. Instances
hidden in the render are left out. Distances are converted to mm with the camera's
unit_scale.
BOP example in the Quick start
What it needs
Steps in the generating Compose, in every datapoint:
Render()as PNG or JPEG:rgb/. Required.Pose(classes):scene_gt.json. Required.CameraData()with a perspective camera:scene_camera.json. Required.Segmentation(classes, full_masks=True)withper="instance"orper="both"and the same classes asPose:mask/,mask_visib/andscene_gt_info.json(visible fraction, boxes, pixel counts). Optional, but when any datapoint has masks, every posed instance in every datapoint needs both its masks.Passes(["Depth"]):depth/. Optional.
In the scene: every object of a class must have the same mesh, origin and
scale, in every datapoint, because BOP has one 3D model per class and a pose is
relative to that model's origin. Keep Scale augmentations, shape keys and
other deformations off the posed objects; the export raises when a class's
scale changes. The models themselves (models/obj_<obj_id>.ply, in mm) are not
written; export them from Blender with that scale applied.
Note
An instance of several objects has the pose of its first object, so its other
objects must move rigidly with it. Depth outside the 16-bit range (65535 x
depth_scale mm) and the background are 0.
Parameters:
-
path(str) –generating path with the
<index>.jsonlabels.//paths are relative to the .blend file when running in Blender. -
output(Optional[str], default:None) –BOP dataset folder. None =
<path>/bop. -
classes(Optional[Sequence[str]], default:None) –class names in
obj_idorder (ids start at 1). None = in order of first appearance in the poses. -
scene_id(int, default:0) –number of the scene folder.
-
split(str, default:'train_pbr') –name of the split folder, e.g.
"train_pbr"or"test". -
depth_scale(float, default:1.0) –mm per depth image unit, BOP's
depth_scale.
Returns:
-
str–Path of the scene folder.
Raises:
-
ValueError–a datapoint without poses or camera intrinsics, an image that is not PNG or JPEG, a pose without both masks when the dataset has masks, a class with objects of different scales, or a class in the labels missing from
classes.
Example
export.bop("//dataset", classes=["car", "table"])
augmentation_stats
¶
augmentation_stats(
path: str,
*,
graph_file: str = "augmentations.json",
prefix: str = "",
) -> dict[str, dict]
Compares what the augmentations did over a dataset with what their graph expects.
Reads the graph generating.Augmentations saved and the augmentations record of
every label. For each augmentation it counts the calls (the objects of the
Compose it is in, over all datapoints) and how often it ran, and for the ones with
values in the graph (a Menu with options, a Boolean...) how often each value
was set. Datapoints BBox skipped have no label, so a gap between expected and
observed shows what the skips (or the scene) changed.
An augmentation that changes the same thing for every object (an absolute data
path, Seed) counts once per datapoint, its last call; its expected is None when
a OneOf or a p below 1 between it and the Compose decides per object whether
it is called. An augmentation used in several places of the graph has expected
None too, since its record mixes them.
Parameters:
-
path(str) –the generating path.
-
graph_file(str, default:'augmentations.json') –file name of the graph, as given to
generating.Augmentations. -
prefix(str, default:'') –the
prefixof the generatingCompose: only its labels, graph and skipped datapoints are read.
Returns:
-
dict[str, dict]–`{id: {"type", "name", "expected", "observed", "applied", "calls", "skipped",
-
dict[str, dict]–"values"}}
by the ids of the graph:name` is the one given to the augmentation -
dict[str, dict]–(None without),
skippedthe same counts over the skipped datapoints -
dict[str, dict]–(
{"observed", "applied", "calls"}, fromskipped.jsonl),expectedthe graph's -
dict[str, dict]–probability that it runs per call,
-
dict[str, dict]–observedthe fraction ofcallsit ran in (applied), andvalues -
dict[str, dict]–[{"value", "expected", "observed", "skipped_observed"}]for every value expected -
dict[str, dict]–or set.
Raises:
-
FileNotFoundError–there is no graph file in the folder.
Example
stats = export.augmentation_stats("//dataset")
for node_id, node in stats.items():
print(node_id, node["type"], node["expected"], node["observed"])
skip_stats
¶
skip_stats(path: str, *, prefix: str = '') -> dict
Counts the datapoints generating.BBox skipped, by reason and class.
Reads skipped.jsonl, which generating.Augmentations writes for every skipped
datapoint, and counts the labels with an augmentations record as the kept ones.
Parameters:
-
path(str) –the generating path.
-
prefix(str, default:'') –the
prefixof the generatingCompose: only itsskipped.jsonland labels are read.
Returns:
-
dict–{"kept", "skipped", "reasons": {reason: {"count", "classes": {class: count}}}}, -
dict–where the reason is the
BBoxsetting that skipped it ("max_truncation", -
dict–"max_iou","max_occlusion"), and the class of anmax_iouskip -
dict–is the two classes joined by
" + ".
Example
skips = export.skip_stats("//dataset")
print(skips["skipped"], "of", skips["kept"] + skips["skipped"], "skipped")
for reason, info in skips["reasons"].items():
print(reason, info["count"], info["classes"])
augmentation_report
¶
augmentation_report(
path: str,
output: Optional[str] = None,
*,
graph_file: str = "augmentations.json",
prefix: str = "",
) -> str
Writes an HTML page with the augmentation graph and how the dataset followed it.
The augmentations are drawn as a flowchart: the steps of a Compose or Chain run
left to right in a frame, a OneOf forks to its branches (with their weight and
share) and they join again, and lines are as thick as the probability that they are
reached. Each card has a bar with how often it runs,
expected (the graph) and observed (the dataset, augmentation_stats), and for a
Menu, MaterialSlot or UVMap with its options listed, a Boolean, a
Visibility or a ShadowCatcher, one per value. A difference more than 3 standard errors from
chance (e.g. moved objects skipped more often by BBox because they leave the
frame) is marked. The datapoints BBox skipped are counted by reason (truncation,
IoU, occlusion) and class, and a card's "skips" bar, centered on 0, shows how much
more (red, right, +) or less (green, left, −) often the datapoint was skipped when the
augmentation ran than when it didn't, which shows the augmentations that cause skips.
Clicking a card shows its settings and numbers. The page is one file that needs no
internet, to open in any browser.
Parameters:
-
path(str) –the generating path, with a
generating.Augmentationsstep's output. -
output(Optional[str], default:None) –file to write,
<path>/<prefix>augmentations.htmlby default. -
graph_file(str, default:'augmentations.json') –file name of the graph, as given to
generating.Augmentations. -
prefix(str, default:'') –the
prefixof the generatingCompose: the report covers that run.
Returns:
-
str–The path of the HTML file.
Raises:
-
FileNotFoundError–there is no graph file in the folder.
Example
export.augmentation_report("//dataset") # open dataset/augmentations.html in a browser