Views
No views yet
pip install transformers torch datasets arabic-reshaper python-bidi1import torch
2from transformers import VisionEncoderDecoderModel, AutoTokenizer, AutoImageProcessor
3from PIL import Image
4import arabic_reshaper
5from bidi.algorithm import get_display
6import matplotlib.pyplot as plt
7
8model_name = "shenasa/persian-image-captioning"
9model = VisionEncoderDecoderModel.from_pretrained(model_name)
10tokenizer = AutoTokenizer.from_pretrained(model_name)
11tokenizer.pad_token_id = tokenizer.eos_token_id
12image_processor = AutoImageProcessor.from_pretrained(model_name)
13
14device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15model.to(device)
16
17def generate_caption(image_path):
18 image = Image.open(image_path).convert('RGB')
19 pixel_values = image_processor(image, return_tensors="pt").pixel_values.to(device)
20 with torch.no_grad():
21 output_ids = model.generate(pixel_values)
22 caption = tokenizer.decode(output_ids[0], skip_special_tokens=True)
23 return caption
24
25def visualize_caption(image_path, caption):
26 image = Image.open(image_path).convert('RGB')
27 reshaped_caption = arabic_reshaper.reshape(caption)
28 bidi_text = get_display(reshaped_caption)
29 plt.imshow(image)
30 plt.axis("off")
31 plt.title(bidi_text)
32 plt.show()
33
34# Example
35image_path = "path/to/your/image.jpg"
36caption = generate_caption(image_path)
37visualize_caption(image_path, caption)1@article{asadian2025pic,
2 author = {Asadian, Rasoul and Akhavanpour, Alireza},
3 title = {Persian Text-Image Retrieval: A Framework Based on Image Captioning and Scalable Vector Search},
4 journal = {IEEE CSICC},
5 year = {2025},
6 doi = {10.1109/CSICC65765.2025.10967407},
7 url = {https://ieeexplore.ieee.org/document/10967407}
8}