Views
No views yet

1import torch
2from PIL import Image
3from transformers import (
4 AutoImageProcessor,
5 AutoTokenizer,
6 AutoModelForCausalLM,
7)
8
9
10model_root = "qihoo360/fg-clip2-large"
11model = AutoModelForCausalLM.from_pretrained(model_root,trust_remote_code=True).cuda()
12
13device = model.device
14
15tokenizer = AutoTokenizer.from_pretrained(model_root)
16image_processor = AutoImageProcessor.from_pretrained(model_root)
171def determine_max_value(image):
2 w,h = image.size
3 max_val = (w//16)*(h//16)
4 if max_val > 784:
5 return 1024
6 elif max_val > 576:
7 return 784
8 elif max_val > 256:
9 return 576
10 elif max_val > 128:
11 return 256
12 else:
13 return 128
14
15img_root = "cat_dfclor.jpg"
16image = Image.open(img_root).convert("RGB")
17
18image_input = image_processor(images=image, max_num_patches=determine_max_value(image), return_tensors="pt").to(device)
19
20# NOTE Short captions: max_length=64 walk_type="short"(default)
21# NOTE Long captions: max_length=196 walk_type="long"
22
23captions = [
24"一个简约风格的卧室角落,黑色金属衣架上挂着多件米色和白色的衣物,下方架子放着两双浅色鞋子,旁边是一盆绿植,左侧可见一张铺有白色床单和灰色枕头的床。",
25"一个简约风格的卧室角落,黑色金属衣架上挂着多件红色和蓝色的衣物,下方架子放着两双黑色高跟鞋,旁边是一盆绿植,左侧可见一张铺有白色床单和灰色枕头的床。",
26"一个简约风格的卧室角落,黑色金属衣架上挂着多件米色和白色的衣物,下方架子放着两双运动鞋,旁边是一盆仙人掌,左侧可见一张铺有白色床单和灰色枕头的床。",
27"一个繁忙的街头市场,摊位上摆满水果,背景是高楼大厦,人们在喧闹中购物。"
28]
29captions = [caption.lower() for caption in captions]
30
31caption_input = tokenizer(captions, padding="max_length", max_length=196, truncation=True, return_tensors="pt").to(device)
32
33
34with torch.no_grad():
35 image_feature = model.get_image_features(**image_input)
36 text_feature = model.get_text_features(**caption_input,walk_type="long")
37 image_feature = image_feature / image_feature.norm(p=2, dim=-1, keepdim=True)
38 text_feature = text_feature / text_feature.norm(p=2, dim=-1, keepdim=True)
39
40logits_per_image = image_feature @ text_feature.T
41logit_scale, logit_bias = model.logit_scale.to(text_feature.device), model.logit_bias.to(text_feature.device)
42logits_per_image = logits_per_image * logit_scale.exp() + logit_bias
43# The original Github example does not print probabilities for retrieval, keeping consistency.
1
2import math
3import matplotlib
4matplotlib.use('Agg')
5import matplotlib.pyplot as plt
6
7
8img_root = "cat_dfclor.jpg"
9image = Image.open(img_root).convert("RGB")
10# The 'resize_short_edge' function is not defined in the snippet or provided context.
11# Assuming 'cat_dfclor.jpg' is pre-processed or the model handles sizing.
12# image = resize_short_edge(image,target_size=2048)
13
14image_input = image_processor(images=image, max_num_patches=16384, return_tensors="pt").to(device)
15captions = ["电脑","黑猫","窗户","window","white cat","book"]
16
17with torch.no_grad():
18 dense_image_feature = model.get_image_dense_feature(**image_input)
19
20 spatial_values = image_input["spatial_shapes"][0]
21 real_h = spatial_values[0].item()
22 real_w = spatial_values[1].item()
23 real_pixel_tokens_num = real_w*real_h
24 dense_image_feature = dense_image_feature[0][:real_pixel_tokens_num]
25 captions = [caption.lower() for caption in captions]
26 caption_input = tokenizer(captions, padding="max_length", max_length=64, truncation=True, return_tensors="pt").to(device)
27
28 text_feature = model.get_text_features(**caption_input, walk_type="box")
29 text_feature = text_feature / text_feature.norm(p=2, dim=-1, keepdim=True)
30 dense_image_feature = dense_image_feature / dense_image_feature.norm(p=2, dim=-1, keepdim=True)
31
32similarity = dense_image_feature @ text_feature.T
33similarity = similarity.cpu()
34
35
36num_classes = len(captions)
37cols = 3
38rows = (num_classes + cols - 1) // cols
39
40
41aspect_ratio = real_w / real_h
42
43fig_width_inch = 3 * cols
44fig_height_inch = fig_width_inch / aspect_ratio * rows / cols
45
46fig, axes = plt.subplots(rows, cols, figsize=(fig_width_inch, fig_height_inch))
47fig.subplots_adjust(wspace=0.01, hspace=0.01)
48
49if num_classes == 1:
50 axes = [axes]
51else:
52 axes = axes.flatten()
53
54for cls_index in range(num_classes):
55 similarity_map = similarity[:, cls_index].cpu().numpy()
56 show_image = similarity_map.reshape((real_h, real_w))
57
58 ax = axes[cls_index]
59 ax.imshow(show_image, cmap='viridis', aspect='equal')
60 ax.set_xticks([])
61 ax.set_yticks([])
62 ax.axis('off')
63
64
65for idx in range(num_classes, len(axes)):
66 axes[idx].axis('off')
67
68savename = "FGCLIP2_dfcolor_cat_all_2K.png"
69plt.savefig(savename, dpi=150, bbox_inches='tight', pad_inches=0.05)
70plt.close()
@article{xie2025fg2,
title={FG-CLIP 2: A Bilingual Fine-grained Vision-language Alignment Model},
author={Xie, Chunyu and Wang, Bin and Kong, Fanjing and Li, Jincheng and Liang, Dawei and Ao, Ji and Leng, Dawei and Yin, Yuhui},
journal={arXiv preprint arXiv:2510.10921},
year={2025}
}@article{xie2025fg,
title={FG-CLIP: Fine-Grained Visual and Textual Alignment},
author={Xie, Chunyu and Wang, Bin and Kong, Fanjing and Li, Jincheng and Liang, Dawei and Zhang, Gengshen and Leng, Dawei and Yin, Yuhui},
journal={arXiv preprint arXiv:2505.05071},
year={2025}
}