2. BLIP模型图像描述生成

任务说明

本案例使用Salesforce预训练的BLIP-base模型(图像描述生成版本),对COCO 2014验证集中的图像生成文本描述,并计算生成描述与人工标注描述之间的CIDEr指标。你需要准备COCO验证集图像及标注文件,运行评估脚本后获得量化评分。

实现方案

整体流程分为三个环节:加载BLIP模型与处理器 → 对每张验证图像生成描述 → 使用pycocoevalcap计算CIDEr。代码采用最小可复现实现,不包含训练或微调逻辑。依赖环境需安装PyTorch、transformers、torchvision、pycocoevalcap及Pillow。

代码实现


import json
import os
import torch
from PIL import Image
from transformers import BlipProcessor, BlipForConditionalGeneration
from pycocotools.coco import COCO
from pycocoevalcap.cider.cider import Cider

# ========== 配置 ==========
COCO_ANNOT_FILE = "annotations/captions_val2014.json"   # COCO标注文件路径
COCO_IMAGE_DIR = "val2014"                               # 验证集图像目录
SAMPLE_SIZE = 50                                         # 评估图像数量(可调)
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
MODEL_NAME = "Salesforce/blip-image-captioning-base"

# ========== 1. 加载模型与处理器 ==========
print("加载BLIP模型...")
processor = BlipProcessor.from_pretrained(MODEL_NAME)
model = BlipForConditionalGeneration.from_pretrained(MODEL_NAME).to(DEVICE)
model.eval()

# ========== 2. 加载COCO标注 ==========
print("加载COCO标注...")
coco = COCO(COCO_ANNOT_FILE)
image_ids = coco.getImgIds()[:SAMPLE_SIZE]   # 取前SAMPLE_SIZE张图像

# ========== 3. 生成描述 ==========
print("生成图像描述...")
generated_captions = {}   # {image_id: "生成的描述"}
reference_captions = {}   # {image_id: ["人工标注1", "人工标注2", ...]}

for img_id in image_ids:
    img_info = coco.loadImgs(img_id)[0]
    img_path = os.path.join(COCO_IMAGE_DIR, img_info["file_name"])
    
    # 加载并处理图像
    image = Image.open(img_path).convert("RGB")
    inputs = processor(image, return_tensors="pt").to(DEVICE)
    
    # 生成描述(beam search)
    with torch.no_grad():
        out = model.generate(
            **inputs,
            max_new_tokens=50,
            num_beams=3,
            do_sample=False
        )
    caption = processor.decode(out[0], skip_special_tokens=True)
    generated_captions[img_id] = caption
    
    # 获取人工标注(取前5条)
    ann_ids = coco.getAnnIds(imgIds=img_id)
    anns = coco.loadAnns(ann_ids)
    refs = [ann["caption"] for ann in anns[:5]]
    reference_captions[img_id] = refs

# ========== 4. 计算CIDEr ==========
print("计算CIDEr指标...")
# 将数据转换为pycocoevalcap要求的格式
gts = {str(k): [{"caption": c} for c in v] for k, v in reference_captions.items()}
res = {str(k): [{"caption": v}] for k, v in generated_captions.items()}

cider_scorer = Cider()
score, _ = cider_scorer.compute_score(gts, res)
print(f"CIDEr (基于{SAMPLE_SIZE}张图像): {score:.4f}")

运行与验证

依赖安装:


pip install torch torchvision transformers pycocotools pycocoevalcap pillow

数据准备:从COCO官网下载2014验证集图像(val2014.zip)及标注文件(annotations_trainval2014.zip),解压后保持目录结构:val2014/存放图像,annotations/captions_val2014.json存放标注。

执行:将上述代码保存为blip_cider_eval.py,修改文件路径后运行:


python blip_cider_eval.py

判定标准:程序正常结束并输出CIDEr分数。由于BLIP是强预训练模型,在COCO验证集上CIDEr值通常在1.0以上(越高越好)。若输出分数明显偏低(如低于0.5),应检查图像路径是否正确、生成描述是否为空或异常。首次运行会自动下载模型权重(约990MB),需保持网络畅通。

BLIP图像描述生成与CIDEr评估流程 ① 数据准备 COCO标注文件 captions_val2014.json 验证集图像目录 val2014/*.jpg ② 模型加载 BLIPProcessor BlipForConditionalGeneration 预训练权重: Salesforce/blip-image-captioning-base ③ 描述生成 图像预处理 beam search解码 max_new_tokens=50 num_beams=3 ④ CIDEr指标计算 生成描述 (res) 人工标注 (gts) pycocoevalcap → Cider.compute_score() 输出:CIDEr 分数 验证路径:运行脚本 → 观察输出CIDEr值 → 与已知BLIP基线(约1.1~1.3)对比