data-and-postprocessing
Load PytorchWildlife image folders, apply inference transforms, serialize detection and classification results, create visualizations and crops, separate images safely, and process video or demo UI outputs.
- License 许可
- MIT
- 最近更新
- 2026-09-03
- Stars
- ★ 351
- Forks
- 27
01 前言 Front Matter
- name
- data-and-postprocessing
- license
- MIT
- metadata
- { "disco-role": "operating" }
- description
- Load PytorchWildlife image folders, apply inference transforms, serialize detection and classification results, create visualizations and crops, separate images safely, and process video or demo UI outputs.
- disable-model-invocation
- true
02 资源文件 5
- 参考文档references/data-formats.md3.6 KB
- 参考文档references/post-processing.md5.6 KB
- 参考文档references/troubleshooting.md4.7 KB
- 参考文档references/video-and-ui.md3.9 KB
- 脚本scripts/separate_detection_results.py7.1 KB
03 SKILL.md 正文
Data and post-processing
Use this sub-skill after a detector or classifier has produced results, or when preparing image inputs for those models. It covers public PytorchWildlife 1.3.0 data, transform, utility, video, and demo contracts. It does not choose or construct models, train models, or run a web service.
Route first
- Route detector construction, model versions, confidence semantics, and
detector result generation to
detection. - Route classifier construction, class catalogs, and crop classification to
classification; use this skill for the crop dataset and output boundary. - Route audio, spectrogram, and bioacoustic files to
bioacoustics. - Route training, annotation splits, and legacy fine-tuning to
fine-tuning. - Keep this skill for folder loading, transforms, result files, visual output, video callbacks, and Gradio/Docker caveats.
Read the focused contracts before implementation:
- data-formats.md — folder datasets, crop assumptions, extensions, RGB/path/size outputs, and transforms.
- post-processing.md — visualizers, crop files, detection/dot/TimeLapse/classification JSON, and separation rules.
- video-and-ui.md — callback/fps/codec contract, UI limits, security, installation, and Docker overview.
- troubleshooting.md — predictable failures and recovery actions.
- separate_detection_results.py — a standard-library, validation-first copy helper for untrusted JSON.
Dataset decision table
| Need | Use | Item contract |
|---|---|---|
| Direct classifier images | ClassificationImageFolder |
(image, path) |
| Detector image batches | DetectionImageFolder |
(image, path, (H, W)) |
| Classify detector animal boxes | DetectionCrops |
(crop, path) |
ClassificationImageFolder and DetectionImageFolder recursively discover
case-insensitive .jpg, .jpeg, .png, .ppm, .bmp, .pgm, .tif,
.tiff, and .webp files. Both open and convert each image to RGB before the
optional transform. The detection dataset records original (height, width)
before transformation; the classification dataset does not return that size.
Paths are filesystem paths, not class labels. The native recursive discovery
order is not a stable dataset-order guarantee, so sort paths if reproducible
ordering matters.
DetectionCrops consumes detection result dictionaries containing img_id
and a supervision.Detections object. It selects detections whose
class_id == animal_cls_id (default 0), resolves path_head / img_id when
provided, crops image-space xyxy, converts to RGB, and applies its transform.
It assumes files and boxes are valid and does not return detection indices;
keep crop and classifier result order aligned.
Transform decision table
| Model input | Transform | Defaults and output |
|---|---|---|
| MegaDetector v5 | MegaDetector_v5_Transform |
target 1280, stride 32, CHW float tensor, letterbox/pad |
| Classifier inference | Classification_Inference_Transform |
target 224, tensor, ImageNet normalization |
letterbox preserves aspect ratio, scales to [0,1], and pads with
114/255; it accepts a PIL image or CHW tensor. scaleup=False prevents
upscaling. Classification resize is square and does not preserve aspect
ratio. Full parameters and coordinate cautions are in
data-formats.md.
Result boundary
The usual result entry has img_id, detections.xyxy,
detections.class_id, detections.confidence, and model labels. Before
serializing, establish a portable image-id policy and validate that every
parallel array has the same length. Use exclude_file_path only when its
exact native path prefix is known; inspect output for machine-local paths.
Choose output deliberately:
save_detection_imagesfor RGB images with boxes and labels.save_detection_images_dotsfor dot-style annotations such as HerdNet.save_crop_imagesfor one crop per detection.save_detection_jsonfor integerxyxyboxes and parallel category and confidence lists.save_detection_json_as_dotsfor center-point JSON.save_detection_timelapse_jsonfor normalizedxywhTimeLapse boxes.- Classification serializers only after verifying detector/crop alignment.
These functions create output files/directories and do not remove source images. Keep generated outputs outside recursively scanned input folders. Use post-processing.md for exact schemas, empty-detection behavior, normalized-coordinate requirements, and the current image-level classification association behavior.
Safe image separation
The native detection_folder_separation copies each referenced image into
Animal or No_animal, preserving nested paths. Category 0 is positive only
when confidence is strictly greater than the supplied threshold; equality is
negative. Empty results are negative. For user-supplied JSON, prefer the
bundled script:
python scripts/separate_detection_results.py --json detections.json \
--source-root /data/images --destination /data/separated --threshold 0.2
The helper requires relative non-traversing img_id values, validates lists
and source containment, aggregates duplicate image ids, copies with copy2,
refuses destinations inside the source tree, and refuses overwrite unless
--overwrite is explicit. Run its bounded fixture check with:
python scripts/separate_detection_results.py --self-test
Video and demo UI
process_video invokes callback(frame: numpy.ndarray, index: int) -> numpy.ndarray on RGB frames and writes an RGB result after converting for the
codec. target_fps can cause frame stride and index is the sampled-frame
index. Start model instances once outside the callback. mp4v is the default;
avc1 may improve browser playback only with a compatible OpenCV build.
The Gradio demo supports single images, ZIP batches, folder separation, and
video with FPS/codec controls, but has no authentication and is not a
multi-tenant service. Keep it on loopback with share=False, bound temporary
files, upload sizes, and archive paths; do not launch it during verification.
Large uploads, Windows batch/video uploads, browser codecs, and missing ffmpeg
or OpenCV encoder support are known caveats. Installation and Docker are
reference-only deployment paths; do not pull images or launch services as a
routine data operation. See video-and-ui.md.
04 同仓库更多 Skills
passnet-triton-opt
Make a single PassNet Triton kernel fast AND numerically faithful: performance model (when a replacement can win at all), block/grid/warp tuning, autotune policy, launch overhead, and per-op numeric recipes to pass the dtype baseline tolerances. Use when a pass matches and is correct but speedup below expected, or when correctness fails by small numeric margins.
passnet-solve
END-TO-END playbook for solving one PassNet sample: analyze the computation graphs, decide the optimization strategy (what to fuse, what to replace, what to leave alone), drive the iteration loop, and maximize the sample score. This is the ENTRY skill — invoke it first for any PassNet optimization task; it tells you when to use passnet-pattern-fusion, passnet-triton-opt and passnet-feedback.
passnet-skill
PassNet GPU kernel optimization via compiler passes. Design and implement Triton-based optimization passes, create pass files under ./pass_dir/, self-evaluate with pass_evaluator, and iterate to maximize GPU speedup.
passnet-pattern-fusion
Author PassNet pass files: write patterns that actually MATCH the FX graph, pick fusion regions (which ops to absorb into one Triton kernel), and structure multi-pass submissions with the mandatory shared-dispatch architecture. Use when creating or fixing pattern()/replacement_args()/replacement_func() files, when a pass "failed to match", or when deciding how to fuse multiple kernels/ops.
passnet-orchestrate
Round/batch planning and decision support for PassNet graph optimization. Use for multi-sample triage, worker allocation, eval-budget policy, and post-eval keep/revert decisions. For solving one concrete sample end to end, use passnet-solve as the entry skill; consult this skill only when you need broader planning or a specific decision gate.
passnet-feedback
Fast, deterministic feedback for PassNet work: pre-flight pattern/match verification WITHOUT burning a GPU evaluation, per-node bottleneck analysis of a sample's graphs, and eval-log parsing into per-variant status + estimated score + failure classification. Use BEFORE every GPU evaluation (check_pattern), at the START of a sample (analyze_graph), and AFTER every evaluation (parse_eval_log).