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-base"
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
7def resize_short_edge(image, target_size=2048):
8
9 if isinstance(image, str):
10 image = Image.open(image)
11
12 width, height = image.size
13 short_edge = min(width, height)
14
15 if short_edge >= target_size:
16 return image
17
18 scale = target_size / short_edge
19 new_width = int(width * scale)
20 new_height = int(height * scale)
21
22 resized_image = image.resize((new_width, new_height))
23
24 return resized_image
25
26img_root = "cat_dfclor.jpg"
27image = Image.open(img_root).convert("RGB")
28# The 'resize_short_edge' function is not defined in the snippet or provided context.
29# Assuming 'cat_dfclor.jpg' is pre-processed or the model handles sizing.
30# image = resize_short_edge(image,target_size=2048)
31
32image_input = image_processor(images=image, max_num_patches=16384, return_tensors="pt").to(device)
33captions = ["电脑","黑猫","窗户","window","white cat","book"]
34
35with torch.no_grad():
36 dense_image_feature = model.get_image_dense_feature(**image_input)
37
38 spatial_values = image_input["spatial_shapes"][0]
39 real_h = spatial_values[0].item()
40 real_w = spatial_values[1].item()
41 real_pixel_tokens_num = real_w*real_h
42 dense_image_feature = dense_image_feature[0][:real_pixel_tokens_num]
43 captions = [caption.lower() for caption in captions]
44 caption_input = tokenizer(captions, padding="max_length", max_length=64, truncation=True, return_tensors="pt").to(device)
45
46 text_feature = model.get_text_features(**caption_input, walk_type="box")
47 text_feature = text_feature / text_feature.norm(p=2, dim=-1, keepdim=True)
48 dense_image_feature = dense_image_feature / dense_image_feature.norm(p=2, dim=-1, keepdim=True)
49
50similarity = dense_image_feature @ text_feature.T
51similarity = similarity.cpu()
52
53
54num_classes = len(captions)
55cols = 3
56rows = (num_classes + cols - 1) // cols
57
58
59aspect_ratio = real_w / real_h
60
61fig_width_inch = 3 * cols
62fig_height_inch = fig_width_inch / aspect_ratio * rows / cols
63
64fig, axes = plt.subplots(rows, cols, figsize=(fig_width_inch, fig_height_inch))
65fig.subplots_adjust(wspace=0.01, hspace=0.01)
66
67if num_classes == 1:
68 axes = [axes]
69else:
70 axes = axes.flatten()
71
72for cls_index in range(num_classes):
73 similarity_map = similarity[:, cls_index].cpu().numpy()
74 show_image = similarity_map.reshape((real_h, real_w))
75
76 ax = axes[cls_index]
77 ax.imshow(show_image, cmap='viridis', aspect='equal')
78 ax.set_xticks([])
79 ax.set_yticks([])
80 ax.axis('off')
81
82
83for idx in range(num_classes, len(axes)):
84 axes[idx].axis('off')
85
86savename = "FGCLIP2_dfcolor_cat_all_2K.png"
87plt.savefig(savename, dpi=150, bbox_inches='tight', pad_inches=0.05)
88plt.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}
}