原理
使用GPT-2模型处理文本,做decoder。
使用google的vit-base-patch16-224模型处理图像,做encoder。
最后通过VisionEncoderDecoderModel将这两个模型粘起来。
如下图所示。
代码
1、导入相关的包
from transformers import (VisionEncoderDecoderModel,
AutoTokenizer,ViTImageProcessor)
import torch
from PIL import Image
2、加载模型
# VIT_MODEL_NAME_OR_PATH = "./vit-base-patch16-224"
# GPT_MODEL_NAME_OR_PATH = "./gpt2_chinese"
# vision_encoder_decoder_model_name_or_path = "./vit-gpt2-image-chinese-captioning"
VIT_MODEL_NAME_OR_PATH = "google/vit-base-patch16-224"
GPT_MODEL_NAME_OR_PATH = "yuanzhoulvpi/gpt2_chinese"
vision_encoder_decoder_model_name_or_path = "vit-gpt2-image-chinese-captioning"
processor = ViTImageProcessor.from_pretrained(VIT_MODEL_NAME_OR_PATH)
tokenizer = AutoTokenizer.from_pretrained(GPT_MODEL_NAME_OR_PATH)
model = VisionEncoderDecoderModel.from_pretrained(vision_encoder_decoder_model_name_or_path)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
如果网速过慢,可以先把模型下载到本地,下载方法:下载huggingface-transformers模型至本地,并使用from_pretrained方法加载
3、推理,生成文本
max_length = 16
num_beams = 4
gen_kwargs = {"max_length": max_length, "num_beams": num_beams}
def predict_step(image_paths):
images = []
for image_path in image_paths:
i_image = Image.open(image_path)
if i_image.mode != "RGB":
i_image = i_image.convert(mode="RGB")
images.append(i_image)
pixel_values = processor(images=images, return_tensors="pt").pixel_values
pixel_values = pixel_values.to(device)
output_ids = model.generate(pixel_values, **gen_kwargs)
preds = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
preds = [pred.strip() for pred in preds]
return preds
predict_step(['./images/a.jpg'])
4、效果
我上传的图片为:
生成的文本为: