開始使用免費開始

影像前處理

在這個練習中,你會使用 flickr 資料集。它包含 30,000 張影像與對應標題,用來對影像進行前處理。這些前處理能讓影像資料適合用於 Hugging Face 的各種模型任務,例如從影像產生文字標題。這次你要為下列影像產生一段文字說明:

Photo of 2 people with 1 playing the guitar

資料集(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]}')
編輯並執行程式碼