@@ -127,7 +127,7 @@ def insert_image(
127127 original_dtype = x .dtype
128128 data = np .copy (x )
129129 if channels_first :
130- data = data .transpose ([ 1 , 2 , 0 ] )
130+ data = np .transpose (data , ( 1 , 2 , 0 ) )
131131
132132 height , width , num_channels = data .shape
133133
@@ -136,37 +136,36 @@ def insert_image(
136136 backdoored_img = Image .new ("RGBA" , (width , height ), 0 ) # height and width are swapped for PIL
137137
138138 if no_color :
139- backdoored_input = Image .fromarray ((data * 255 ).astype (" uint8" ).squeeze (axis = 2 ), mode = mode )
139+ backdoored_input = Image .fromarray ((data * 255 ).astype (np . uint8 ).squeeze (axis = 2 ), mode = mode )
140140 else :
141- backdoored_input = Image .fromarray ((data * 255 ).astype (" uint8" ), mode = mode )
141+ backdoored_input = Image .fromarray ((data * 255 ).astype (np . uint8 ), mode = mode )
142142
143143 orig_img .paste (backdoored_input )
144144
145145 trigger = Image .open (backdoor_path ).convert ("RGBA" )
146- if size :
147- trigger = trigger .resize (size )
146+ if size is not None :
147+ trigger = trigger .resize (( size [ 1 ], size [ 0 ])) # height and width are swapped for PIL
148148
149149 backdoor_width , backdoor_height = trigger .size # height and width are swapped for PIL
150150
151151 if backdoor_width > width or backdoor_height > height :
152152 raise ValueError ("Backdoor does not fit inside original image" )
153153
154154 if random :
155- x_shift = np .random .randint (width - backdoor_width )
156- y_shift = np .random .randint (height - backdoor_height )
155+ x_shift = np .random .randint (width - backdoor_width + 1 )
156+ y_shift = np .random .randint (height - backdoor_height + 1 )
157157
158158 backdoored_img .paste (trigger , (x_shift , y_shift ), mask = trigger )
159159 composite = Image .alpha_composite (orig_img , backdoored_img )
160160 backdoored_img = Image .blend (orig_img , composite , blend )
161-
162161 backdoored_img = backdoored_img .convert (mode )
163162
164- res = np .array (backdoored_img ) / 255.0
163+ res = np .asarray (backdoored_img ) / 255.0
165164
166165 if no_color :
167166 res = np .expand_dims (res , 2 )
168167
169168 if channels_first :
170- res = res .transpose ([ 2 , 0 , 1 ] )
169+ res = np .transpose (res , ( 2 , 0 , 1 ) )
171170
172171 return res .astype (original_dtype )
0 commit comments