图像预处理
在本练习中,您将使用 flickr 数据集,该数据集包含 30,000 张图像及其对应的字幕,用于对图像执行预处理操作。预处理可以让图像数据适配 Hugging Face 的模型任务,例如从图像生成文本。在这里,您将为下图生成一段文字描述:

数据集(dataset)已按如下结构加载:
Dataset({
features: ['image', 'caption', 'sentids', 'split', 'img_id', 'filename'],
num_rows: 10
})
图像字幕模型(model)已加载。
本练习是课程的一部分
使用 Hugging Face 的多模态模型
练习说明
- 从数据集下标为
5的元素中读取图像。 - 加载预训练模型
Salesforce/blip-image-captioning-base的图像处理器(BlipProcessor)。 - 在
image上执行处理器,确保指定返回 PyTorch 张量(pt)。 - 使用
model的.generate()方法生成图像字幕。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Load the image from index 5 of the dataset
image = dataset[5]["____"]
# Load the image processor of the pretrained model
processor = ____.____("Salesforce/blip-image-captioning-base")
# Preprocess the image
inputs = ____(images=____, return_tensors="pt")
# Generate a caption using the model
output = ____(**inputs)
print(f'Generated caption: {processor.decode(output[0])}')
print(f'Original caption: {dataset[5]["caption"][0]}')