Transformers
Classifies images with pretrained models and configurable image processors.
- Downloads / mo
- 120.5M
- Stars
- 169.2K
- Last release
- 5.23.0
- License
- Apache-2.0
Strengths
- Scores new labels without training. Use zero-shot-image-classification with a compatible image-text checkpoint.
- Chooses image preprocessing backends. Select torchvision or PIL with the image processor’s backend option.
Limitations
- ViT can rescale inputs twice. Set do_rescale=False for images already between zero and one.
- PIL preprocessing is CPU-only. Select the torchvision backend when preprocessing must run on a GPU.
Quickstart
from transformers import pipeline classifier = pipeline("image-classification", model="google/vit-base-patch16-224") print(classifier("image.jpg"))
Transformers examples
def predict_batch( self, input_batch: List[ImageClassificationEngineInput] ) -> List[ImageClassificationEngineOutput]: """Run inference on a batch of inputs.""" import torch if not input_batch: return [] if self._model is None or self._processor is None or self._device is None: raise RuntimeError("Engine not initialized. Call initialize() first.") images = [item.image.convert("RGB") for item in input_batch] inputs = self._processor(images=images, return_tensors="pt").to( self._device, self._model.dtype ) with torch.inference_mode(): outputs = self._model(**inputs) # type: ignore[operator] probs_batch = torch.softmax(outputs.logits, dim=-1) batch_outputs: List[ImageClassificationEngineOutput] = [] for input_item, probs_vector in zip(input_batch, probs_batch): # Use topk for efficiency when top_k is specified if self.options.top_k is not None: k = min(self.options.top_k, len(probs_vector)) scores, labels = torch.topk(probs_vector, k=k) else: scores, labels = torch.sort(probs_vector, descending=True) batch_outputs.append( self._build_output( input_item=input_item, labels=labels.tolist(), scores=scores.tolist(), ) ) return batch_outputs