Views
No views yet
1from transformers import AutoImageProcessor, LwDetrForObjectDetection
2import torch
3from PIL import Image
4import requests
5
6url = "http://images.cocodataset.org/val2017/000000039769.jpg"
7image = Image.open(requests.get(url, stream=True).raw)
8
9processor = AutoImageProcessor.from_pretrained("AnnaZhang/lwdetr_xlarge_60e_coco")
10model = LwDetrForObjectDetection.from_pretrained("AnnaZhang/lwdetr_xlarge_60e_coco")
11
12inputs = processor(images=image, return_tensors="pt")
13outputs = model(**inputs)
14
15# convert outputs (bounding boxes and class logits) to COCO API
16# let's only keep detections with score > 0.7
17target_sizes = torch.tensor([image.size[::-1]])
18results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.7)[0]
19
20for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
21 box = [round(i, 2) for i in box.tolist()]
22 print(
23 f"Detected {model.config.id2label[label.item()]} with confidence "
24 f"{round(score.item(), 3)} at location {box}"
25 )Detected cat with confidence 0.945 at location [7.89, 54.09, 314.97, 472.48]
Detected cat with confidence 0.94 at location [345.47, 22.71, 640.24, 372.13]
Detected couch with confidence 0.912 at location [1.56, 1.29, 639.97, 474.73]
Detected remote with confidence 0.893 at location [39.96, 73.65, 175.91, 117.11]
Detected remote with confidence 0.783 at location [333.79, 77.38, 370.37, 186.66]1@article{chen2024lw,
2 title={LW-DETR: A Transformer Replacement to YOLO for Real-Time Detection},
3 author={Chen, Qiang and Su, Xiangbo and Zhang, Xinyu and Wang, Jian and Chen, Jiahui and Shen, Yunpeng and Han, Chuchu and Chen, Ziliang and Xu, Weixiang and Li, Fanrong and others},
4 journal={arXiv preprint arXiv:2406.03459},
5 year={2024}
6 }