Views
No views yet
1from transformers import pipeline
2
3image_captioner = pipeline("image-to-text", model="Abdou/vit-swin-base-224-gpt2-image-captioning")
4# infer the caption
5caption = image_captioner("http://images.cocodataset.org/test-stuff2017/000000000019.jpg")[0]['generated_text']
6print(f"caption: {caption}")
71from transformers import VisionEncoderDecoderModel, GPT2TokenizerFast, ViTImageProcessor
2import torch
3import os
4import urllib.parse as parse
5from PIL import Image
6import requests
7
8# a function to determine whether a string is a URL or not
9def is_url(string):
10 try:
11 result = parse.urlparse(string)
12 return all([result.scheme, result.netloc, result.path])
13 except:
14 return False
15
16# a function to load an image
17def load_image(image_path):
18 if is_url(image_path):
19 return Image.open(requests.get(image_path, stream=True).raw)
20 elif os.path.exists(image_path):
21 return Image.open(image_path)
22
23# a function to perform inference
24def get_caption(model, image_processor, tokenizer, image_path):
25 image = load_image(image_path)
26 # preprocess the image
27 img = image_processor(image, return_tensors="pt").to(device)
28 # generate the caption (using greedy decoding by default)
29 output = model.generate(**img)
30 # decode the output
31 caption = tokenizer.batch_decode(output, skip_special_tokens=True)[0]
32 return caption
33
34device = "cuda" if torch.cuda.is_available() else "cpu"
35# load the fine-tuned image captioning model and corresponding tokenizer and image processor
36model = VisionEncoderDecoderModel.from_pretrained("Abdou/vit-swin-base-224-gpt2-image-captioning").to(device)
37tokenizer = GPT2TokenizerFast.from_pretrained("Abdou/vit-swin-base-224-gpt2-image-captioning")
38image_processor = ViTImageProcessor.from_pretrained("Abdou/vit-swin-base-224-gpt2-image-captioning")
39
40# target image
41url = "http://images.cocodataset.org/test-stuff2017/000000000019.jpg"
42# get the caption
43caption = get_caption(model, image_processor, tokenizer, url)
44print(f"caption: {caption}")
45
46Two cows laying in a field with a sky background.| Training Loss | Epoch | Step | Validation Loss | Rouge1 | Rouge2 | Rougel | Rougelsum | Bleu | Gen Len |
|---|---|---|---|---|---|---|---|---|---|
| 1.0018 | 0.38 | 2000 | 0.8860 | 38.6537 | 13.8145 | 35.3932 | 35.3935 | 8.2448 | 11.2946 |
| 0.8827 | 0.75 | 4000 | 0.8395 | 40.0458 | 14.8829 | 36.5321 | 36.5366 | 9.1169 | 11.2946 |
| 0.8378 | 1.13 | 6000 | 0.8140 | 41.2736 | 15.9576 | 37.5504 | 37.5512 | 9.871 | 11.2946 |
| 0.7913 | 1.51 | 8000 | 0.8012 | 41.6642 | 16.1987 | 37.8786 | 37.8891 | 10.0786 | 11.2946 |
| 0.7794 | 1.89 | 10000 | 0.7933 | 41.9119 | 16.3738 | 38.1062 | 38.1292 | 10.288 | 11.2946 |