@@ -78,49 +78,30 @@ def expand_crop_region(crop_region, processing_width, processing_height, image_w
7878
7979
8080def expand_too_small_crop_region (crop_region , processing_width , processing_height , image_width , image_height ):
81- """expands crop region to not have width and height smaller then processing_width and processing_height"""
81+ """expands a crop_region to not have dimensions smaller than processing_dimensions"""
82+
83+ def _expand_segment (c1 , c2 , processing_dimension , image_dimension ):
84+ """expands the segment given by c1 c2 to the desired_dimension but not exceeding the boundaries of the image_dimension"""
85+ if (diff := processing_dimension + c1 - c2 ) > 0 :
86+ # if the region is smaller than processing_dimension, extend both sides equally
87+ diff_l = diff // 2
88+ c1 -= diff_l
89+ c2 += diff - diff_l
90+ if c1 < 0 : # shift the region to the right by c1
91+ c2 = min (c2 - c1 , image_dimension ) # ensure c2 is within image_dimension
92+ c1 = 0
93+ elif c2 >= image_dimension : # shift the region to the left by (c2 - image_dimension)
94+ c1 = max (c1 - c2 + image_dimension , 0 ) # ensure c1 is not below 0
95+ c2 = image_dimension
96+ return c1 , c2
8297
8398 x1 , y1 , x2 , y2 = crop_region
84-
85- desired_w = processing_width
86- diff_w = desired_w - (x2 - x1 )
87- if diff_w > 0 :
88- diff_w_l = diff_w // 2
89- diff_w_r = diff_w - diff_w_l
90- x1 -= diff_w_l
91- x2 += diff_w_r
92- if x2 >= image_width :
93- diff = x2 - image_width
94- x2 -= diff
95- x1 -= diff
96- if x1 < 0 :
97- x2 -= x1
98- x1 -= x1
99- if x2 >= image_width :
100- x2 = image_width
101-
102- desired_h = processing_height
103- diff_h = desired_h - (y2 - y1 )
104- if diff_h > 0 :
105- diff_h_u = diff_h // 2
106- diff_h_d = diff_h - diff_h_u
107- y1 -= diff_h_u
108- y2 += diff_h_d
109- if y2 >= image_height :
110- diff = y2 - image_height
111- y2 -= diff
112- y1 -= diff
113- if y1 < 0 :
114- y2 -= y1
115- y1 -= y1
116- if y2 >= image_height :
117- y2 = image_height
118-
119- if diff_h > 0 or diff_w > 0 :
120- print ("Crop region was smaller then resolution and has been corrected" )
121-
122- return x1 , y1 , x2 , y2
123-
99+ x1 , x2 = _expand_segment (x1 , x2 , processing_width , image_width )
100+ y1 , y2 = _expand_segment (y1 , y2 , processing_height , image_height )
101+ new_crop_region = x1 , y1 , x2 , y2
102+ if new_crop_region != crop_region :
103+ print (f"Crop region { crop_region } was smaller then process resolution and has been expanded to { new_crop_region } " )
104+ return new_crop_region
124105
125106
126107def fill (image , mask ):
0 commit comments