Views
No views yet
transformers and qwen-vl-utils installed:1pip install transformers
2pip install qwen-vl-utils1from transformers import Qwen2_5_VLForConditionalGeneration, AutoTokenizer, AutoProcessor
2from qwen_vl_utils import process_vision_info
3import torch
4
5# Load model and processor
6model_name = "ShaoRun/RS-EoT-7B"
7model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
8 model_name, torch_dtype="auto", device_map="auto"
9)
10processor = AutoProcessor.from_pretrained(model_name)
11
12# Define input image (assumes demo.jpg is in the current directory)
13image_path = "./demo.jpg"
14
15messages = [
16 {
17 "role": "user",
18 "content": [
19 {"type": "image", "image": image_path},
20 {"type": "text", "text": "How many cars in this image?"},
21 ],
22 }
23]
24
25# Preparation for inference
26text = processor.apply_chat_template(
27 messages, tokenize=False, add_generation_prompt=True
28)
29image_inputs, video_inputs = process_vision_info(messages)
30inputs = processor(
31 text=[text],
32 images=image_inputs,
33 videos=video_inputs,
34 padding=True,
35 return_tensors="pt",
36)
37inputs = inputs.to("cuda")
38
39# Inference
40generated_ids = model.generate(**inputs, max_new_tokens=4096)
41generated_ids_trimmed = [
42 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
43]
44output_text = processor.batch_decode(
45 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
46)
47
48print(output_text[0])1import re
2import torch
3from PIL import Image, ImageDraw, ImageFont
4from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
5from qwen_vl_utils import process_vision_info
6
7# --- Helper Functions for Parsing and Visualization ---
8
9def extract_bbox_list_in(text: str) -> list[list[float]]:
10 """Extracts bounding boxes from the model output text."""
11 boxes = []
12 text = re.sub(r'\\([{}\[\]":,])', r'\1', text)
13 # Pattern to find lists of numbers like [x1, y1, x2, y2]
14 pattern = re.compile(r'\[\s*(.*?)\s*\]', flags=re.IGNORECASE | re.DOTALL)
15 matches = pattern.findall(text)
16
17 number_pattern = r'-?\d+\.\d+|-?\d+'
18 for match in matches:
19 nums = re.findall(number_pattern, match)
20 if len(nums) >= 4:
21 # Take the first 4 numbers as the box
22 box = [float(num) for num in nums[:4]]
23 boxes.append(box)
24 return boxes
25
26def visualize_bboxes(img: Image.Image, boxes: list[list[float]], color=(0, 255, 0), width=3) -> Image.Image:
27 """Draws bounding boxes on the image."""
28 out = img.copy()
29 draw = ImageDraw.Draw(out)
30 W, H = img.size
31
32 for b in boxes:
33 if len(b) < 4: continue
34 x1, y1, x2, y2 = b[:4]
35
36 # Ensure coordinates are within bounds
37 x1, y1 = max(0, min(W-1, x1)), max(0, min(H-1, y1))
38 x2, y2 = max(0, min(W-1, x2)), max(0, min(H-1, y2))
39
40 # Draw rectangle with thickness
41 draw.rectangle([x1, y1, x2, y2], outline=color, width=width)
42
43 return out
44
45# --- Main Inference Code ---
46
47model_name = "ShaoRun/RS-EoT-7B"
48model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
49 model_name, torch_dtype="auto", device_map="auto"
50)
51processor = AutoProcessor.from_pretrained(model_name)
52
53# Load Image
54image_path = "./demo.jpg"
55image = Image.open(image_path).convert('RGB')
56
57messages = [
58 {
59 "role": "user",
60 "content": [
61 {"type": "image", "image": image},
62 {"type": "text", "text": 'Locate the black car parked on the right in the remote sensing image. Return the coordinates as "[x1, y1, x2, y2]".'},
63 ],
64 }
65]
66
67# Process Inputs
68text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
69image_inputs, video_inputs = process_vision_info(messages)
70inputs = processor(
71 text=[text],
72 images=image_inputs,
73 videos=video_inputs,
74 padding=True,
75 return_tensors="pt",
76)
77inputs = inputs.to("cuda")
78
79# Generate
80generated_ids = model.generate(**inputs, max_new_tokens=4096)
81generated_ids_trimmed = [
82 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
83]
84response = processor.batch_decode(
85 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
86)[0]
87
88print(f"Model Response:\n{response}")
89
90# Parse and Visualize
91answer_part = response.split("</think>")[-1]
92detection = extract_bbox_list_in(answer_part)
93
94if detection:
95 print(f"Detected BBoxes: {detection}")
96 vis_img = visualize_bboxes(image, detection)
97 vis_img.save("./res.jpg")
98 print("Visualization saved to ./res.jpg")
99else:
100 print("No bounding boxes detected in the response.")1@article{shao2025asking,
2 title={Asking like Socrates: Socrates helps VLMs understand remote sensing images},
3 author={Shao, Run and Li, Ziyu and Zhang, Zhaoyang and Xu, Linrui and He, Xinran and Yuan, Hongyuan and He, Bolei and Dai, Yongxing and Yan, Yiming and Chen, Yijun and others},
4 journal={arXiv preprint arXiv:2511.22396},
5 year={2025}
6}