yang1002's picture
Document annotated NIR subset and RNFD paper
e9f5413 verified
Raw History Blame Contribute Delete
26.5 kB
"""Build and verify a small lossless RGB/NIR subset without changing sources."""
from __future__ import annotations
import argparse
import csv
import hashlib
import io
import json
import shutil
import sys
import time
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from PIL import Image
DISTANCES = [
"10.646", "20.444", "30.594", "40.603", "50.601", "60.912",
"70.476", "80.753", "90.673", "100.374", "110.452", "120.808",
"130.484", "140.201", "150.271",
]
NIR_DISTANCES = set(DISTANCES[:12])
def sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def sample_evenly(items: list[Path], count: int) -> list[Path]:
if len(items) < count:
raise ValueError(f"Insufficient samples: {len(items)} < {count}")
return [items[i * (len(items) - 1) // (count - 1)] for i in range(count)]
def xml_signature(node: ET.Element):
return (
node.tag, tuple(sorted(node.attrib.items())), (node.text or "").strip(),
tuple(xml_signature(child) for child in node
if child.tag not in {"filename", "path"}),
)
def collect_jobs(source: Path, calibration_right_source: Path) -> tuple[list[dict], dict]:
jobs = []
counts = {}
for distance in DISTANCES:
folder = source / distance
complete = sorted(
(p for p in folder.glob("Image0_*.bmp")
if (folder / p.name.replace("Image0_", "Image1_", 1)).is_file()),
key=lambda p: p.name,
)
counts[distance] = len(complete)
for first in sample_evenly(complete, 5):
sample_id = first.stem.split("_", 1)[1]
for camera in (("Image0", "Image1", "Image2") if distance in NIR_DISTANCES
else ("Image0", "Image1")):
image = folder / f"{camera}_{sample_id}.bmp"
annotation = source / "labelimg" / distance / f"{image.stem}.xml"
root = ET.fromstring(annotation.read_bytes())
if root.findtext("filename") != image.name:
raise ValueError(f"Annotation filename mismatch: {annotation}")
jobs.append(dict(
source=image.relative_to(source).as_posix(),
file_name=image.relative_to(source).with_suffix(".png").as_posix(),
sample_id=f"{distance}_{sample_id}", distance_group=distance,
camera_id=camera, modality="NIR" if camera == "Image2" else "RGB",
purpose="distance",
annotation_file=annotation.relative_to(source).as_posix(),
))
calibration = sorted((source / "calibration" / "left").glob("Image0_*.bmp"),
key=lambda p: p.name)
counts["calibration/left"] = len(calibration)
counts["calibration/right"] = len(list(calibration_right_source.glob("Image1_*.bmp")))
for image in sample_evenly(calibration, 20):
jobs.append(dict(
source=image.relative_to(source).as_posix(),
file_name=image.relative_to(source).with_suffix(".png").as_posix(),
sample_id="calibration_" + image.stem.split("_", 1)[1],
distance_group="", camera_id="Image0", modality="RGB", purpose="calibration",
annotation_file="",
))
right_image = calibration_right_source / image.name.replace("Image0_", "Image1_", 1)
if not right_image.is_file():
raise FileNotFoundError(f"Matching calibration right image missing: {right_image}")
jobs.append(dict(
source=right_image.name, source_collection="calibration_right",
file_name=f"calibration/right/{right_image.stem}.png",
sample_id="calibration_" + image.stem.split("_", 1)[1],
distance_group="", camera_id="Image1", modality="RGB", purpose="calibration",
annotation_file="",
))
infra_image = source / "calibration" / "infra" / image.name.replace("Image0_", "Image2_", 1)
if not infra_image.is_file():
raise FileNotFoundError(f"Matching calibration infrared image missing: {infra_image}")
jobs.append(dict(
source=infra_image.relative_to(source).as_posix(),
file_name=infra_image.relative_to(source).with_suffix(".png").as_posix(),
sample_id="calibration_" + image.stem.split("_", 1)[1],
distance_group="", camera_id="Image2", modality="NIR", purpose="calibration",
annotation_file="",
))
for job in jobs:
job.setdefault("source_collection", "main")
assert len(jobs) == 270
assert sum(bool(j["annotation_file"]) for j in jobs) == 210
return jobs, counts
def convert_job(source: Path, destination: Path, job: dict, calibration_right_source: Path) -> dict:
source_root = calibration_right_source if job["source_collection"] == "calibration_right" else source
original_path = source_root / job["source"]
target = destination / job["file_name"]
target.parent.mkdir(parents=True, exist_ok=True)
raw = original_path.read_bytes()
source_hash = sha256(raw)
source_size = len(raw)
with Image.open(io.BytesIO(raw)) as original:
original.load()
expected_mode = "L" if job["camera_id"] == "Image2" else "RGB"
if original.mode != expected_mode:
raise ValueError(f"Unexpected mode {original.mode}: {original_path}")
pixel_hash = sha256(original.tobytes())
if not target.exists():
temporary = target.with_suffix(".png.part")
original.save(temporary, format="PNG", compress_level=6)
temporary.replace(target)
encoded = target.read_bytes()
with Image.open(io.BytesIO(encoded)) as converted:
converted.load()
if (converted.size != original.size or converted.mode != original.mode
or sha256(converted.tobytes()) != pixel_hash):
raise ValueError(f"Lossless pixel validation failed: {target}")
width, height = original.size
mode = original.mode
record = dict(
**job, width=width, height=height, mode=mode,
source_bytes=source_size, output_bytes=len(encoded),
source_sha256=source_hash, output_sha256=sha256(encoded),
decoded_pixels_sha256=pixel_hash, pixels_verified_equal=True,
)
if job["annotation_file"]:
xml_source = source / job["annotation_file"]
xml_target = destination / job["annotation_file"]
xml_bytes = xml_source.read_bytes()
root = ET.fromstring(xml_bytes)
signature = xml_signature(root)
if (int(root.findtext("size/width")) != width
or int(root.findtext("size/height")) != height):
raise ValueError(f"Annotation dimensions mismatch: {xml_source}")
root.find("filename").text = target.name
path_node = root.find("path")
if path_node is None:
path_node = ET.SubElement(root, "path")
path_node.text = job["file_name"]
xml_target.parent.mkdir(parents=True, exist_ok=True)
ET.ElementTree(root).write(xml_target, encoding="utf-8", xml_declaration=True)
result = ET.fromstring(xml_target.read_bytes())
if xml_signature(result) != signature:
raise ValueError(f"Annotation content changed: {xml_target}")
if result.findtext("filename") != target.name or result.findtext("path") != job["file_name"]:
raise ValueError(f"Annotation reference mismatch: {xml_target}")
record.update(
annotation_source_sha256=sha256(xml_bytes),
annotation_output_sha256=sha256(xml_target.read_bytes()),
annotation_content_verified_equal=True,
object_count=len(root.findall("object")),
)
return record
def write_readme(destination: Path, summary: dict) -> None:
rows = "\n".join(
f"| {d} | 5 | {15 if d in NIR_DISTANCES else 10} | "
f"{15 if d in NIR_DISTANCES else 10} |"
for d in DISTANCES
)
text = """---
pretty_name: Binocular Flame Localization Dataset - Compact Subset
language:
- en
tags:
- stereo-vision
- calibration
- object-detection
- near-infrared
size_categories:
- n<1K
---
# Binocular Flame Localization Dataset - Compact Subset
This repository provides a **compact subset of binocular flame-localization data** from the original `20241227` collection, supplemented with corresponding calibration images from `20241227_origin/calibration/all/right`. It is associated with the [Small-Scale Fire Datasets project](https://github.com/yang1002-life/small-fire_datasets) and the paper [FireDet: A framework for precise detection and localization of small-scale fire](https://doi.org/10.1016/j.firesaf.2026.104737), published in *Fire Safety Journal*, Volume 162, Article 104737, 2026. It is also associated with [RNFD: An Adaptive RGB-NIR Heterogeneous Fusion System for Robust Fire Detection and Precise Localization](https://doi.org/10.1155/int/7387105), published in *International Journal of Intelligent Systems*, 2026, Article 7387105.
The release contains **270 original-resolution, lossless PNG images** and **210 Pascal VOC XML detection annotations**. `Image0` and `Image1` are RGB; `Image2` contains grayscale near-infrared (NIR) images. These counts describe this compact release, not the full dataset totals reported by the associated papers. No training/test split is defined.
For a separate visible-light detection release, see the [Comprehensive Flame Dataset - Validation Split](https://huggingface.co/datasets/yang1002/comprehensive-flame-dataset-validation), which contains 2,424 validation images with YOLO TXT and original XML annotations. That release is not a split of this binocular subset.
## Dataset composition
Each of the 15 distance-group directories contains five same-numbered `Image0 + Image1` RGB pairs. The first 12 groups also contain the five same-numbered, annotated `Image2` NIR images. Selected `Image2` images in `130.484`, `140.201`, and `150.271` have no XML annotations, so they are omitted. The localization portion has **210 images and 210 XML files**.
The calibration portion contains **20 same-numbered RGB/NIR triplets, or 60 images**: `left` contains `Image0`, the supplementary `right` directory contains `Image1`, and `infra` contains `Image2`. Calibration images have no detection XML files.
| Distance-group directory | RGB pairs | Images | XML files |
| --- | ---: | ---: | ---: |
__ROWS__
| calibration/left | See total | 20 | 0 |
| calibration/right | See total | 20 | 0 |
| calibration/infra | See total | 20 | 0 |
| **Total** | **75 localization pairs and 20 calibration triplets** | **270** | **210** |
All images are **5472 x 3648 pixels**. RGB images have three channels; NIR images are single-channel grayscale. Distance-group directory names are preserved verbatim; their units have not been confirmed. `Image0` and `Image1` are original camera identifiers, and their physical left/right mapping for the localization images has not been confirmed. The original calibration directory name `left` is not additional evidence for the physical orientation of the localization cameras.
## Sampling and lossless conversion
Within each distance group, complete `Image0 + Image1` pairs are sorted by image number. Five pairs are selected using zero-based indices `floor(i * (N - 1) / 4)`, for `i = 0, ..., 4`. In the first 12 groups, same-numbered `Image2` images are included only where source XML annotations exist. For calibration, the sorted left images are sampled at indices `floor(i * (N - 1) / 19)`, for `i = 0, ..., 19`; same-numbered images from the supplementary right directory and original `calibration/infra` directory form 20 triplets. Both rules include the first and last entries.
Sample identifiers from the `70` directory are already represented in `70.476`, so they are not sampled twice. GA outputs, unrelated programs, caches and other processing outputs are excluded; `build_subset.py` is retained as the reproducible construction script. BMP-to-PNG conversion does not resize, crop or change the image mode. Each output was compared with its source using dimensions, mode and the SHA-256 of decoded pixels; all decoded pixels were verified identical.
## File organization and annotations
```text
10.646/ ... 120.808/ # Five Image0 / Image1 / Image2 triplets per group
130.484/ ... 150.271/ # Five Image0 / Image1 pairs per group
calibration/left/ # 20 Image0 PNGs
calibration/right/ # 20 same-numbered Image1 PNGs
calibration/infra/ # 20 same-numbered Image2 PNGs
labelimg/<distance_group>/ # XML annotations for the selected localization images
metadata.csv # 270 rows of image metadata
manifest.jsonl # Source, output, pixel and annotation verification records
summary.json # Counts, sizes and verification results
SHA256SUMS.txt # SHA-256 of all release files except this checksum file
build_subset.py # Reproducible sampling and verification script
README.md # Dataset card
```
Image numbers are unchanged; only the extension was converted from `.bmp` to `.png`. Each of the 210 localization images has a corresponding **Pascal VOC XML** annotation. XML `filename` values were updated to the PNG filename, and `path` values are relative to the dataset root. Classes, bounding-box coordinates and all other annotation content are unchanged. Resolve XML image paths relative to the dataset root.
`metadata.csv` is UTF-8 and contains these fields: `file_name` (relative image path), `sample_id` (group identifier prefixed by distance group or calibration), `distance_group` (original directory name; empty for calibration), `camera_id`, `purpose` (`distance` or `calibration`), `annotation_file` (relative XML path; empty for calibration), and `modality` (`RGB` or `NIR`). Images in the same numbered group share a `sample_id`. Read `distance_group` as a string.
## Download
Install the Hugging Face client and download this compact subset:
```bash
pip install --upgrade huggingface_hub
hf download yang1002/Binocular-Flame-Localization-Dataset --repo-type dataset --local-dir Binocular-Flame-Localization-Dataset
```
Or use Python:
```python
from huggingface_hub import snapshot_download
snapshot_download(
repo_id="yang1002/Binocular-Flame-Localization-Dataset",
repo_type="dataset",
local_dir="Binocular-Flame-Localization-Dataset",
)
```
For reproducible downloads, pass a specific commit SHA as `--revision` to the CLI or `revision=` to `snapshot_download`. `metadata.csv` links each image through `file_name`; see the [Hugging Face image dataset documentation](https://huggingface.co/docs/hub/datasets-image) for additional context. The release whitelist consists of the files listed in `SHA256SUMS.txt`, plus that checksum file itself; Windows thumbnail caches and other extra files are excluded. Hugging Face's repository metadata file `.gitattributes` is outside this release whitelist.
## Reading example
```python
import csv
from pathlib import Path
from PIL import Image
root = Path("Binocular-Flame-Localization-Dataset")
with (root / "metadata.csv").open(encoding="utf-8", newline="") as f:
samples = list(csv.DictReader(f))
with Image.open(root / samples[0]["file_name"]) as image:
print(samples[0]["sample_id"], image.size)
```
## Verification and size
The release contains 270 images and 210 XML files. All 270 image conversions were verified to preserve decoded pixels, and all 210 annotations were verified unchanged except for filename and path updates. The 190 PNG images and 150 XML files from the first compact release retain their original hashes. These checks establish preservation during conversion; they do not independently establish annotation quality.
The selected source BMP images total __SOURCE_GIB__ GiB; the PNG images total __OUTPUT_GIB__ GiB, or __RATIO__% of the original BMP size (a reduction of __REDUCTION__%). See `summary.json` for the release's total size, including documentation and checksum files but excluding the Hub-generated `.gitattributes` file.
`manifest.jsonl` records SHA-256 values for source images, PNG outputs and annotations. Records with `source_collection=main` use source paths relative to the original `20241227` collection; those with `source_collection=calibration_right` use source paths relative to the supplementary right directory. `SHA256SUMS.txt` checks the integrity of downloaded release files. On systems with `sha256sum`, run the following from the dataset root:
```bash
sha256sum --check SHA256SUMS.txt
```
## Reproducible construction
Python 3.10+ and Pillow are required. The destination must be a new directory:
```text
python build_subset.py --source <original-20241227-directory> --calibration-right-source <supplementary-right-directory> --destination <new-output-directory> --workers 3
```
If construction is interrupted, add `--resume` with the same output directory. Existing PNGs are still reverified against their source images; verification is not skipped. Reconstruction requires the original source collections, which are not included in this compact release.
## Usage limitations, license and provenance
This is a small subset intended for demonstration, download and workflow validation. No training/test split has been defined. Calibration-board specifications, camera parameters and distance units have not been confirmed. The original annotations are retained without an additional claim about their quality.
**No dataset license has been specified for this release.** License and authorization terms remain to be supplied by the data owner. Public availability does not itself grant a particular reuse license; do not infer one from the project code, dependencies or paper. Consult the dataset owner about reuse and applicable source-specific terms.
## Citation
If you use this release, cite the associated papers as applicable:
```bibtex
@article{dai2026firedet,
title = {FireDet: A framework for precise detection and localization of small-scale fire},
author = {Dai, Jinyang and Cao, Qiuyang and Song, Xiaoning and Pan, Bence and Zhang, Qixing},
journal = {Fire Safety Journal},
volume = {162},
pages = {104737},
year = {2026},
doi = {10.1016/j.firesaf.2026.104737}
}
@article{dai2026rnfd,
title = {RNFD: An Adaptive RGB-NIR Heterogeneous Fusion System for Robust Fire Detection and Precise Localization},
author = {Dai, Jinyang and Cao, Qiuyang and Song, Xiaoning and Zhang, Qixing},
journal = {International Journal of Intelligent Systems},
year = {2026},
pages = {7387105},
doi = {10.1155/int/7387105}
}
```
This repository is a compact localization subset; it does not contain all data used in either paper.
"""
replacements = {
"__ROWS__": rows,
"__SOURCE_GIB__": f"{summary['source_image_bytes'] / 1024**3:.3f}",
"__OUTPUT_GIB__": f"{summary['output_image_bytes'] / 1024**3:.3f}",
"__RATIO__": f"{100 * summary['png_to_bmp_ratio']:.2f}",
"__REDUCTION__": f"{100 * (1 - summary['png_to_bmp_ratio']):.2f}",
}
for key, value in replacements.items():
text = text.replace(key, value)
(destination / "README.md").write_text(text, encoding="utf-8")
def finalize_outputs(destination: Path, summary: dict) -> None:
# Explorer can create these caches on network shares during the build.
def clean_thumbnail_caches():
for cache in destination.rglob("*"):
if cache.is_file() and cache.name.lower() == "thumbs.db":
cache.chmod(cache.stat().st_mode | 0o200)
cache.unlink(missing_ok=True)
clean_thumbnail_caches()
write_readme(destination, summary)
build_script = destination / "build_subset.py"
if Path(__file__).resolve() != build_script.resolve():
shutil.copyfile(__file__, build_script)
records = [json.loads(line) for line in (destination / "manifest.jsonl").read_text(encoding="utf-8").splitlines()]
expected = {r["file_name"] for r in records}
expected.update(r["annotation_file"] for r in records if r["annotation_file"])
expected.update({"metadata.csv", "manifest.jsonl", "README.md", "build_subset.py", "summary.json", "SHA256SUMS.txt"})
summary_path = destination / "summary.json"
checksum_path = destination / "SHA256SUMS.txt"
summary["total_file_count_including_checksums"] = len(expected)
summary["total_output_bytes_including_checksums"] = 0
hash_cache = {}
for _ in range(8):
summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
delivered = [destination / relative for relative in sorted(expected - {"SHA256SUMS.txt"})]
checksum_lines = []
for p in delivered:
relative = p.relative_to(destination).as_posix()
if relative not in hash_cache or p == summary_path:
hash_cache[relative] = sha256(p.read_bytes())
checksum_lines.append(f"{hash_cache[relative]} {relative}\n")
checksum_path.write_text("".join(checksum_lines), encoding="utf-8", newline="\n")
total = sum(p.stat().st_size for p in delivered) + checksum_path.stat().st_size
if total == summary["total_output_bytes_including_checksums"]:
break
summary["total_output_bytes_including_checksums"] = total
else:
raise ValueError("Could not stabilize output size summary")
clean_thumbnail_caches()
actual = {p.relative_to(destination).as_posix() for p in destination.rglob("*") if p.is_file()}
if actual != expected:
raise ValueError(f"Unexpected delivery files: extra={actual-expected}, missing={expected-actual}")
def main() -> None:
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source", required=True, type=Path)
parser.add_argument("--calibration-right-source", required=True, type=Path)
parser.add_argument("--destination", required=True, type=Path)
parser.add_argument("--workers", type=int, default=3)
parser.add_argument("--resume", action="store_true")
args = parser.parse_args()
source, destination = args.source.resolve(), args.destination.resolve()
calibration_right_source = args.calibration_right_source.resolve()
if source == destination or source in destination.parents or destination in source.parents:
raise ValueError("Source and destination must be separate, non-nested directories")
if destination.exists() and not args.resume:
raise FileExistsError(f"Destination already exists: {destination}")
if destination == calibration_right_source or calibration_right_source in destination.parents or destination in calibration_right_source.parents:
raise ValueError("Destination must not overlap calibration right source")
jobs, available_counts = collect_jobs(source, calibration_right_source)
print(f"Preflight OK: {len(jobs)} images, 210 annotations; workers={args.workers}", flush=True)
destination.mkdir(parents=False, exist_ok=args.resume)
started = time.monotonic()
records_by_name = {}
with ThreadPoolExecutor(max_workers=args.workers) as executor:
futures = [executor.submit(convert_job, source, destination, job, calibration_right_source) for job in jobs]
for i, future in enumerate(as_completed(futures), 1):
record = future.result()
records_by_name[record["file_name"]] = record
if i == 1 or i % 5 == 0:
print(f"Verified {i}/270: {record['file_name']} ({time.monotonic()-started:.1f}s)", flush=True)
records = [records_by_name[job["file_name"]] for job in jobs]
fields = ["file_name", "sample_id", "distance_group", "camera_id", "purpose", "annotation_file", "modality"]
with (destination / "metadata.csv").open("w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
writer.writeheader()
writer.writerows(records)
with (destination / "manifest.jsonl").open("w", encoding="utf-8", newline="\n") as f:
for record in records:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
pngs = list(destination.rglob("*.png"))
xmls = list(destination.rglob("*.xml"))
assert len(pngs) == 270 and len(xmls) == 210
assert not list(destination.rglob("*.part"))
summary = dict(
status="verified", distance_groups=DISTANCES,
distance_pair_count=75, distance_image_count=210,
calibration_pair_count=20, calibration_image_count=60, image_count=len(pngs), annotation_count=len(xmls),
available_complete_pairs_or_calibration_images=available_counts,
source_image_bytes=sum(r["source_bytes"] for r in records),
output_image_bytes=sum(r["output_bytes"] for r in records),
pixels_verified_equal_count=sum(r["pixels_verified_equal"] for r in records),
annotations_verified_equal_count=sum(r.get("annotation_content_verified_equal", False) for r in records),
image2_file_count=80, width=5472, height=3648,
distance_unit=None, image0_image1_left_right_mapping=None, license=None,
sampling_rule="sorted complete pairs: floor(i*(N-1)/4), i=0..4; calibration: floor(i*(N-1)/19), i=0..19",
elapsed_seconds=round(time.monotonic()-started, 2),
)
assert {(r["width"], r["height"]) for r in records} == {(5472, 3648)}
assert sum(r["camera_id"] == "Image2" for r in records) == 80
summary["png_to_bmp_ratio"] = summary["output_image_bytes"] / summary["source_image_bytes"]
finalize_outputs(destination, summary)
print(json.dumps(summary, ensure_ascii=False, indent=2), flush=True)
print(f"COMPLETE: {destination}", flush=True)
if __name__ == "__main__":
main()