Lab_10 / stat_lab_10.py
chayanee's picture
Upload stat_lab_10.py
558c170
# -*- coding: utf-8 -*-
"""stat_lab_10.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1M9jt20Xv08CFH0RJOpWe8aXT62PqGrKu
"""
!python -m pip install transformers accelerate sentencepiece emoji pythainlp --quiet
!python -m pip install --no-deps thai2transformers==0.1.2 --quiet
"""# image Detection"""
!pip install timm
"""## pipline"""
# Use a pipeline as a high-level helper
from transformers import pipeline
pipe = pipeline("object-detection", model="facebook/detr-resnet-50")
"""## Load model"""
# Load model directly
from transformers import AutoFeatureExtractor, AutoModelForObjectDetection
extractor = AutoFeatureExtractor.from_pretrained("facebook/detr-resnet-50")
model = AutoModelForObjectDetection.from_pretrained("facebook/detr-resnet-50")
"""## Use model"""
from transformers import DetrImageProcessor, DetrForObjectDetection
import torch
from PIL import Image
import requests
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
inputs = processor(images=image, return_tensors="pt")
outputs = model(**inputs)
# convert outputs (bounding boxes and class logits) to COCO API
# let's only keep detections with score > 0.9
target_sizes = torch.tensor([image.size[::-1]])
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
box = [round(i, 2) for i in box.tolist()]
print(
f"Detected {model.config.id2label[label.item()]} with confidence "
f"{round(score.item(), 3)} at location {box}"
)