Skip to content

Commit 87b7ed9

Browse files
committed
compact expand_too_small_crop_region
1 parent 2cb3c2d commit 87b7ed9

File tree

1 file changed

+19
-40
lines changed

1 file changed

+19
-40
lines changed

modules/masking.py

Lines changed: 19 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -80,47 +80,26 @@ def expand_crop_region(crop_region, processing_width, processing_height, image_w
8080
def expand_too_small_crop_region(crop_region, processing_width, processing_height, image_width, image_height):
8181
"""expands crop region to not have width and height smaller then processing_width and processing_height"""
8282

83-
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
83+
def _expand(c1, c2, processing_dimension, image_dimension):
84+
if (diff := processing_dimension - (c2 - c1)) > 0:
85+
diff_w_l = diff // 2
86+
c1 -= diff_w_l
87+
c2 += diff - diff_w_l
88+
if c2 >= image_dimension:
89+
c1 -= c2 - image_dimension
90+
c2 = image_dimension
91+
if c1 < 0:
92+
c2 = min(c2 - c1, image_dimension)
93+
c1 = 0
94+
return c1, c2
12395

96+
x1, y1, x2, y2 = crop_region
97+
x1, x2 = _expand(x1, x2, processing_width, image_width)
98+
y1, y2 = _expand(y1, y2, processing_height, image_height)
99+
new_crop_region = x1, y1, x2, y2
100+
if new_crop_region != crop_region:
101+
print(f"Crop region {crop_region} was smaller then resolution and has been expanded to {new_crop_region}")
102+
return new_crop_region
124103

125104

126105
def fill(image, mask):

0 commit comments

Comments
 (0)