Local preservation snapshot, not a new deployment or simulation acceptance.
71 lines
3.5 KiB
Python
71 lines
3.5 KiB
Python
"""Bounded recorded-image qualification. Produces no navigation command."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
import torch
|
|
from PIL import Image
|
|
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--context", action="store_true")
|
|
args = parser.parse_args()
|
|
descriptor = json.loads(Path("/adapter/model.json").read_text())
|
|
for name, expected in descriptor["files"].items():
|
|
digest = hashlib.sha256()
|
|
with (Path("/assets") / name).open("rb") as stream:
|
|
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
|
digest.update(chunk)
|
|
assert digest.hexdigest() == expected, name
|
|
output = Path("/evidence")
|
|
torch.set_num_threads(3)
|
|
processor = AutoImageProcessor.from_pretrained("/assets", local_files_only=True)
|
|
model = Mask2FormerForUniversalSegmentation.from_pretrained("/assets", local_files_only=True).cuda().eval()
|
|
rows = []
|
|
for path in sorted(Path("/inputs").glob("*-crop.jpg")):
|
|
original = Image.open(path).convert("RGB")
|
|
for crop in ((False,) if args.context else (True, False)):
|
|
image = original.crop((100, 0, 700, 600)) if crop else original
|
|
for size in ((1024, 1536, 2048) if args.context else (384, 768)):
|
|
shape = ({"height": round(size * image.height / image.width), "width": size}
|
|
if args.context else {"height": size, "width": size})
|
|
inputs = processor(images=image, return_tensors="pt", size=shape).to("cuda")
|
|
torch.cuda.reset_peak_memory_stats()
|
|
torch.cuda.synchronize()
|
|
begin = time.monotonic()
|
|
with torch.inference_mode():
|
|
prediction = model(**inputs)
|
|
labels = processor.post_process_semantic_segmentation(
|
|
prediction, target_sizes=[(image.height, image.width)]
|
|
)[0].cpu().numpy().astype(np.uint8)
|
|
torch.cuda.synchronize()
|
|
elapsed = time.monotonic() - begin
|
|
key = f"{path.stem}-{'crop' if crop else 'full'}-{size}"
|
|
Image.fromarray(labels).save(output / (key + ".labels.png"))
|
|
# Only visualization: pedestrian area/sidewalk cyan, road red,
|
|
# potential crossing yellow. These colors grant no permissions.
|
|
colors = np.zeros((*labels.shape, 3), dtype=np.uint8)
|
|
colors[np.isin(labels, (11, 15))] = [20, 220, 170]
|
|
colors[labels == 13] = [220, 40, 50]
|
|
colors[np.isin(labels, (8, 23))] = [240, 200, 20]
|
|
Image.blend(image, Image.fromarray(colors), .45).save(output / (key + ".jpg"))
|
|
ids, counts = np.unique(labels, return_counts=True)
|
|
rows.append(dict(case=key, inference_seconds=elapsed,
|
|
input_shape=list(inputs["pixel_values"].shape),
|
|
gpu_peak_bytes=torch.cuda.max_memory_allocated(),
|
|
pedestrian_fraction=float(np.isin(labels, (11, 15)).mean()),
|
|
road_fraction=float((labels == 13).mean()),
|
|
classes={model.config.id2label[int(i)]: int(n) for i, n in zip(ids, counts)}))
|
|
(output / "results.json").write_text(json.dumps(rows, indent=2))
|
|
print(json.dumps(rows[-1]), flush=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|