-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai_image_captioning_system.py
More file actions
42 lines (30 loc) · 1.41 KB
/
ai_image_captioning_system.py
File metadata and controls
42 lines (30 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# -*- coding: utf-8 -*-
"""AI_IMAGE_CAPTIONING_SYSTEM
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/17dn1kTTvteSAZiPRPgyLACsRLmWg5JXU
"""
!pip install torch torchvision transformers pillow
import torch
from transformers import BlipProcessor, BlipForConditionalGeneration
from PIL import Image
# Load BLIP model
device = "cuda" if torch.cuda.is_available() else "cpu"
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(device)
def generate_caption(image_path):
image = Image.open(image_path).convert("RGB")
inputs = processor(images=image, return_tensors="pt").to(device)
with torch.no_grad():
output = model.generate(**inputs, max_length=30)
caption = processor.tokenizer.decode(output[0], skip_special_tokens=True)
return caption
from transformers import pipeline
# Load a simple text-generation model
caption_generator = pipeline("text-generation", model="gpt2", device=0 if torch.cuda.is_available() else -1)
def generate_caption(prompt):
result = caption_generator(prompt, max_length=30, num_return_sequences=1)
return result[0]['generated_text']
image_path = "/content/download.jpg" # Replace with your actual image path
caption = generate_caption(image_path)
print("Generated Caption:", caption)