File size: 9,801 Bytes
70299db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# import torch
# from diffusers import FluxKontextPipeline, FluxPipeline
# from diffusers.utils import load_image

# pipe = FluxKontextPipeline.from_pretrained("/data/xcl/Flux-Kontext/model/FLUX-Kontext-dev", torch_dtype=torch.bfloat16)
# # pipe.to("cuda")
# pipe.enable_model_cpu_offload()
# pipe.image_processor
# input_image = load_image("/data/xcl/dataSet/RSICD_1/test_png/7.png")

# image = pipe(
#   image=input_image,
#   # prompt="Make the paper in the image appear wrinkled and crumpled.",
#   # prompt="Make the handwriting appear messy and wobbly, as if written by a student in a hurry or with uneven hand pressure. Keep the same content and layout.",
#   # prompt="Make the text in the image look like it was handwritten perfunctorily on paper.",
#   # prompt="Reduce overall brightness, add mild shadows, and lower contrast slightly while keeping the handwriting readable.",
#   # prompt="Change the background to look like aged, yellowed paper with slight stains or discoloration.",
#   # prompt="Add a few natural-looking coffee stains or water rings to the background",
#   prompt="Replace planes with trucks.",
#   guidance_scale=2.5,
#   height=512,
#   width=512,
# ).images[0]

# image.save("junshi.png")


# import faulthandler
# # 在import之后直接添加以下启用代码即可
# faulthandler.enable()


# import torch
# from diffusers import FluxKontextPipeline
# from diffusers.utils import load_image

# pipe = FluxKontextPipeline.from_pretrained("/data/xcl/Flux-Kontext/model/FLUX-Kontext-dev", torch_dtype=torch.bfloat16, device_map="balanced")
# # pipe = FluxKontextPipeline.from_pretrained("/data/xcl/model/flux-kontext", torch_dtype=torch.bfloat16)
# # pipe.to("cuda")
# # pipe.enable_model_cpu_offload()

# input_image = load_image("/data/xcl/dataSet/images/8.png")
# # input_image = input_image.resize((512, 512))

# image = pipe(
#   image=input_image,
#   prompt="Replace the ships with airplanes.",
#   guidance_scale=2.5,
# ).images[0]

# image.save("8.png")




# import os
# import json
# from PIL import Image
# import torch
# from diffusers import FluxKontextPipeline

# def process_images():
#     # 初始化管道 - 使用 FluxKontextPipeline
#     pipeline = FluxKontextPipeline.from_pretrained(
#         "/data/xcl/Flux-Kontext/model/FLUX-Kontext-dev",
#         torch_dtype=torch.bfloat16,
#         device_map="balanced"
#     )
#     # 启用 CPU offload 以节省显存
#     # pipeline.enable_model_cpu_offload()
    
#     print("FluxKontextPipeline loaded with automatic device mapping and CPU offload.")
#     pipeline.set_progress_bar_config(disable=None)
    
#     # 路径配置
#     input_dir = "/data/xcl/dataSet/images"
#     output_dir = "/data/xcl/dataSet/images_entity_kontext"
#     json_file = "/data/xcl/dataSet/junshi_images_entity.json"
    
#     # 创建输出目录
#     os.makedirs(output_dir, exist_ok=True)
    
#     # 加载JSON文件
#     with open(json_file, 'r') as f:
#         prompt_dict = json.load(f)
    
#     print(f"Loaded {len(prompt_dict)} image prompts from JSON file.")
    
#     # 处理每张图片
#     processed_count = 0
#     for filename, prompt in prompt_dict.items():
#         input_path = os.path.join(input_dir, filename)
#         output_path = os.path.join(output_dir, filename)
        
#         # 检查输入图片是否存在
#         if not os.path.exists(input_path):
#             print(f"Warning: Image {input_path} not found, skipping...")
#             continue
        
#         # 检查输出是否已存在(避免重复处理)
#         if os.path.exists(output_path):
#             print(f"Warning: Output {output_path} already exists, skipping...")
#             continue
        
#         try:
#             # 加载并处理图片
#             image = Image.open(input_path).convert("RGB")
            
#             width, height = image.size
            
#             # 准备输入参数 - 根据新模型的API调整
#             inputs = {
#                 "image": image,
#                 "prompt": prompt,
#                 "guidance_scale": 2.5,  # 新模型使用 guidance_scale 而不是 true_cfg_scale
#                 "height": height,  # 使用输入图像的高度
#                 "width": width,    # 使用输入图像的宽度
#                 # "generator": torch.manual_seed(0),  # 新模型可能不需要这个参数
#                 # "negative_prompt": " ",  # 新模型可能不需要negative_prompt
#                 # "num_inference_steps": 50,  # 新模型可能使用默认步数
#             }
            
#             # 执行图像编辑
#             with torch.inference_mode():
#                 output = pipeline(**inputs)
#                 output_image = output.images[0]
#                 output_image.save(output_path)
            
#             # 清理GPU缓存
#             if torch.cuda.is_available():
#                 torch.cuda.empty_cache()
            
#             processed_count += 1
#             print(f"Processed {filename} -> {output_path}")
            
#         except Exception as e:
#             print(f"Error processing {filename}: {str(e)}")
#             # 出错时也清理GPU缓存
#             if torch.cuda.is_available():
#                 torch.cuda.empty_cache()
#             continue
    
#     print(f"Processing completed! Successfully processed {processed_count} images.")

# if __name__ == "__main__":
#     process_images()





import os
import json
from PIL import Image
import torch
from diffusers import FluxKontextPipeline

def resize_image_if_needed(image, max_size=1024):
    """
    如果图片的最长边超过max_size,则按比例调整大小
    """
    width, height = image.size
    max_dimension = max(width, height)
    
    if max_dimension <= max_size:
        return image
    
    # 计算新的尺寸,保持宽高比
    if width > height:
        new_width = max_size
        new_height = int(height * (max_size / width))
    else:
        new_height = max_size
        new_width = int(width * (max_size / height))
    
    # 使用LANCZOS重采样以获得更好的质量
    resized_image = image.resize((new_width, new_height), Image.LANCZOS)
    print(f"Resized image from {width}x{height} to {new_width}x{new_height}")
    
    return resized_image

def process_images():
    # 初始化管道 - 使用 FluxKontextPipeline
    pipeline = FluxKontextPipeline.from_pretrained(
        "/data/xcl/Flux-Kontext/model/FLUX-Kontext-dev",
        torch_dtype=torch.bfloat16,
        device_map="balanced"
    )
    # 启用 CPU offload 以节省显存
    # pipeline.enable_model_cpu_offload()
    
    print("FluxKontextPipeline loaded with automatic device mapping and CPU offload.")
    pipeline.set_progress_bar_config(disable=None)
    
    # 路径配置
    input_dir = "/data/xcl/dataSet/images"
    output_dir = "/data/xcl/dataSet/images_entity_background_kontext"
    json_file = "/data/xcl/dataSet/junshi_images_entity_background.json"
    
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)
    
    # 加载JSON文件
    with open(json_file, 'r') as f:
        prompt_dict = json.load(f)
    
    print(f"Loaded {len(prompt_dict)} image prompts from JSON file.")
    
    # 处理每张图片
    processed_count = 0
    for filename, prompt in prompt_dict.items():
        input_path = os.path.join(input_dir, filename)
        output_path = os.path.join(output_dir, filename)
        
        # 检查输入图片是否存在
        if not os.path.exists(input_path):
            print(f"Warning: Image {input_path} not found, skipping...")
            continue
        
        # 检查输出是否已存在(避免重复处理)
        if os.path.exists(output_path):
            print(f"Warning: Output {output_path} already exists, skipping...")
            continue
        
        try:
            # 加载图片
            image = Image.open(input_path).convert("RGB")
            original_width, original_height = image.size
            
            # 检查并调整图片尺寸
            image = resize_image_if_needed(image, max_size=1024)
            new_width, new_height = image.size
            
            # 准备输入参数 - 根据新模型的API调整
            inputs = {
                "image": image,
                "prompt": prompt,
                "guidance_scale": 2.5,  # 新模型使用 guidance_scale 而不是 true_cfg_scale
                "height": new_height,  # 使用调整后的高度
                "width": new_width,    # 使用调整后的宽度
                # "generator": torch.manual_seed(0),  # 新模型可能不需要这个参数
                # "negative_prompt": " ",  # 新模型可能不需要negative_prompt
                # "num_inference_steps": 50,  # 新模型可能使用默认步数
            }
            
            # 执行图像编辑
            with torch.inference_mode():
                output = pipeline(**inputs)
                output_image = output.images[0]
                output_image.save(output_path)
            
            # 清理GPU缓存
            if torch.cuda.is_available():
                torch.cuda.empty_cache()
            
            processed_count += 1
            print(f"Processed {filename} (original: {original_width}x{original_height}, processed: {new_width}x{new_height}) -> {output_path}")
            
        except Exception as e:
            print(f"Error processing {filename}: {str(e)}")
            # 出错时也清理GPU缓存
            if torch.cuda.is_available():
                torch.cuda.empty_cache()
            continue
    
    print(f"Processing completed! Successfully processed {processed_count} images.")

if __name__ == "__main__":
    process_images()