Views
No views yet
Using Multimodal Large Language Models for False Alarm Reduction in Image-based Fire Detection


1from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
2from qwen_vl_utils import process_vision_info
3from modelscope import snapshot_download
4
5
6
7from transformers import Qwen2_5_VLForConditionalGeneration, AutoTokenizer, AutoProcessor
8# from qwen_vl_utils import process_vision_info
9
10model_dir = "" # */gaoqie/Qwen2.5VL-7B-Instruct-fire
11device = "cuda:0"
12# default: Load the model on the available device(s)
13model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
14 model_dir, torch_dtype="bfloat16", device_map=device
15)
16
17# default processer
18processor = AutoProcessor.from_pretrained(model_dir)
19
20# The default range for the number of visual tokens per image in the model is 4-16384. You can set min_pixels and max_pixels according to your needs, such as a token count range of 256-1280, to balance speed and memory usage.
21# min_pixels = 256*28*28
22# max_pixels = 1280*28*28
23# processor = AutoProcessor.from_pretrained(model_dir, min_pixels=min_pixels, max_pixels=max_pixels)
24
25
26def infer(img_path):
27 # 模式1
28 messages = [
29 {
30 "role": "system",
31 "content": "You are a helpful assistant."
32 },
33 {
34 "role": "user",
35 "content": [
36 {
37 "type": "image",
38 "image": img_path,
39 },
40 {
41 "type": "text",
42 "text": "图像中是否存在火焰?详细分析。"
43 }
44 ],
45 }
46 ]
47 # 模式2
48 messages = [
49 {
50 "role": "system",
51 "content": "You are a helpful assistant."
52 },
53 {
54 "role": "user",
55 "content": [
56 {
57 "type": "image",
58 "image": img_path,
59 },
60 {
61 "type": "text",
62 "text": "图像中是否存在火焰?简单回答。"
63 }
64 ],
65 }
66 ]
67 # 模式3
68 messages = [
69 {
70 "role": "system",
71 "content": "You are a helpful assistant."
72 },
73 {
74 "role": "user",
75 "content": [
76 {
77 "type": "image",
78 "image": img_path,
79 },
80 {
81 "type": "text",
82 "text": "图像中是否存在火焰?快速回答。"
83 }
84 ],
85 }
86 ]
87
88 # Preparation for inference
89 text = processor.apply_chat_template(
90 messages, tokenize=False, add_generation_prompt=True
91 )
92
93 image_inputs, video_inputs = process_vision_info(messages)
94
95
96 inputs = processor(
97 text=[text],
98 images=image_inputs,
99 videos=video_inputs,
100 padding=True,
101 return_tensors="pt",
102 )
103 inputs = inputs.to(device)
104
105 # Inference: Generation of the output
106 generated_ids = model.generate(**inputs, max_new_tokens=500)
107 # print(processor.batch_decode(
108 # generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
109 # ))
110 generated_ids_trimmed = [
111 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
112 ]
113 output_text = processor.batch_decode(
114 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
115 )
116
117 output_text = output_text[0]
118 print(output_text)
119
120image_path = ""
121infer(image_path)