-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.py
177 lines (143 loc) · 6.81 KB
/
utils.py
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
import torch
import math
from PIL import Image, ImageDraw, ImageFont
from torch.nn import functional as F
import logging
import os
import numpy as np
import cv2
colors = [
(144, 238, 144),
(255,165,0),
(255, 127, 80),
(255,0,0),
(0,0,255)
]
def concat_images(images,prompt = None):
w = h = 0
for image in images:
w+=image.width
h = image.height
padding = 0
if prompt is not None:
padding = 80
horizontal_concatenated = Image.new('RGB', (w, h+padding),(255,255,255))
width = 0
for image in images:
horizontal_concatenated.paste(image, (width, padding))
width+=image.width
draw = ImageDraw.Draw(horizontal_concatenated)
font = ImageFont.truetype('./ArialBold.ttf', 30)
if prompt is not None:
draw.text((45, 45), prompt, font=font, fill=(0,0,0))
return horizontal_concatenated
def compute_ca_loss_masks(attn_maps_mid, attn_maps_up,dis_matrixs,object_positions,move_rate):
loss = 0
object_number = len(object_positions)
if object_number == 0:
return torch.tensor(0).float().cuda() if torch.cuda.is_available() else torch.tensor(0).float()
# print("len",object_number)
for attn_map_integrated in attn_maps_mid:
attn_map = attn_map_integrated
b, i, j = attn_map.shape
H = W = int(math.sqrt(i))
for obj_idx in range(object_number):
obj_loss = 0
dis_matrix = dis_matrixs[obj_idx]
if (len(dis_matrix[dis_matrix <1e-9 ]) !=0):
nonzero_min = dis_matrix[dis_matrix>1e-9].min()
if (nonzero_min <1e-9) :
nonzero_min = 0.001
dis_matrix+=nonzero_min
dis_matrix = torch.tensor(cv2.resize(dis_matrix, (H, W), interpolation=cv2.INTER_LINEAR)).float().cuda()
for obj_position in object_positions[obj_idx]:
ca_map_obj = attn_map[:, :, obj_position].reshape(b, H, W)
activation_value = (ca_map_obj / dis_matrix).reshape(b, -1).sum(dim=-1)/ca_map_obj.reshape(b, -1).sum(dim=-1)
control_loss = torch.mean((1 - activation_value) ** 2)
obj_loss += control_loss
pre_activation_value = (ca_map_obj*dis_matrix).reshape(b, -1).sum(dim=-1)/ca_map_obj.reshape(b, -1).sum(dim=-1)
move_loss = torch.mean((1-1/pre_activation_value)**2)*move_rate
obj_loss += move_loss
loss += (obj_loss/len(object_positions[obj_idx]))
for attn_map_integrated in attn_maps_up[0]:
attn_map = attn_map_integrated
b, i, j = attn_map.shape
H = W = int(math.sqrt(i))
for obj_idx in range(object_number):
obj_loss = 0
dis_matrix = dis_matrixs[obj_idx]
if (len(dis_matrix[dis_matrix <1e-9 ]) !=0):
nonzero_min = dis_matrix[dis_matrix>1e-9].min()
if (nonzero_min <1e-9) :
nonzero_min = 0.001
dis_matrix+=nonzero_min
dis_matrix = torch.tensor(cv2.resize(dis_matrix, (H, W), interpolation=cv2.INTER_LINEAR)).float().cuda()
for obj_position in object_positions[obj_idx]:
ca_map_obj = attn_map[:, :, obj_position].reshape(b, H, W)
activation_value = (ca_map_obj / dis_matrix).reshape(b, -1).sum(dim=-1)/ca_map_obj.reshape(b, -1).sum(dim=-1)
control_loss = torch.mean((1 - activation_value) ** 2)
obj_loss += control_loss
pre_activation_value = (ca_map_obj*dis_matrix).reshape(b, -1).sum(dim=-1)/ca_map_obj.reshape(b, -1).sum(dim=-1)
move_loss = torch.mean((1-1/pre_activation_value)**2)*move_rate
obj_loss += move_loss
loss += (obj_loss / len(object_positions[obj_idx]))
loss = loss / (object_number * (len(attn_maps_up[0]) + len(attn_maps_mid)))
return loss
def find_tensor_positions(tensor, sub_tensor):
positions = []
for i in range(tensor.shape[0] - sub_tensor.shape[0] + 1):
if torch.equal(tensor[i:i+sub_tensor.shape[0]], sub_tensor):
positions = [i for i in range(i,i+sub_tensor.shape[0])]
return positions
return positions
def Pharse2idx_tokenizer(prompt, phrases,tokenizer):
phrases = [x.strip() for x in phrases.split(';')]
phrase_ids = []
object_positions = []
text_input = tokenizer(prompt, padding="max_length",return_length=True, return_overflowing_tokens=False, max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
for phrase in phrases:
phrase_ids.append(tokenizer(phrase, return_length=True, return_overflowing_tokens=False, max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt").input_ids)
for id in phrase_ids:
position = find_tensor_positions(text_input.input_ids[0],id[0][1:-1])
object_positions.append(position)
return text_input,object_positions
def setup_logger(save_path, logger_name):
logger = logging.getLogger(logger_name)
logger.setLevel(logging.INFO)
# Create a file handler to write logs to a file
file_handler = logging.FileHandler(os.path.join(save_path, f"{logger_name}.log"))
file_handler.setLevel(logging.INFO)
# Create a formatter to format log messages
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Set the formatter for the file handler
file_handler.setFormatter(formatter)
# Add the file handler to the logger
logger.addHandler(file_handler)
return logger
def points_to_masks(points,res=512):
masks = []
for i,point in enumerate(points):
mask = np.zeros((res, res), dtype=np.uint8)
for j in range(len(point) - 1):
point_1 = (int(point[j][0]*512),int(point[j][1]*512))
point_2 = (int(point[j+1][0]*512),int(point[j+1][1]*512))
cv2.line(mask, point_1, point_2, 1, 1)
masks.append(mask)
return masks
def masks_to_distances_matrixs(masks):
distance_matrixs = []
for map in masks:
mask = np.where(map==1,0,1)
distance_transform = cv2.distanceTransform(mask.astype(np.uint8), cv2.DIST_L2, cv2.DIST_MASK_PRECISE)
distance_matrixs.append(distance_transform)
return distance_matrixs
def draw_traces(pil_img, masks, phrases):
draw = ImageDraw.Draw(pil_img)
font = ImageFont.truetype('./ArialBold.ttf', 25)
phrases = [x.strip() for x in phrases.split(';')]
for i,(mask, phrase) in enumerate(zip(masks, phrases)):
indices = np.where(mask == 1)
for y,x in zip(indices[0],indices[1]):
pil_img.putpixel((x, y), colors[i])
draw.text((x + 5, y + 5), phrase, font=font, fill=(255, 0, 0))
return pil_img