Skip to content

Commit 63f398b

Browse files
authored
Merge pull request #8194 from uploadcare/optimize-getbbox
Optimize getbbox() and getextrema() routines
2 parents c9dc34a + e4e2cd6 commit 63f398b

File tree

1 file changed

+54
-25
lines changed

1 file changed

+54
-25
lines changed

src/libImaging/GetBBox.c

Lines changed: 54 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -30,26 +30,57 @@ ImagingGetBBox(Imaging im, int bbox[4], int alpha_only) {
3030
bbox[1] = -1;
3131
bbox[2] = bbox[3] = 0;
3232

33-
#define GETBBOX(image, mask) \
34-
for (y = 0; y < im->ysize; y++) { \
35-
has_data = 0; \
36-
for (x = 0; x < im->xsize; x++) { \
37-
if (im->image[y][x] & mask) { \
38-
has_data = 1; \
39-
if (x < bbox[0]) { \
40-
bbox[0] = x; \
41-
} \
42-
if (x >= bbox[2]) { \
43-
bbox[2] = x + 1; \
44-
} \
45-
} \
46-
} \
47-
if (has_data) { \
48-
if (bbox[1] < 0) { \
49-
bbox[1] = y; \
50-
} \
51-
bbox[3] = y + 1; \
52-
} \
33+
#define GETBBOX(image, mask) \
34+
/* first stage: looking for any pixels from top */ \
35+
for (y = 0; y < im->ysize; y++) { \
36+
has_data = 0; \
37+
for (x = 0; x < im->xsize; x++) { \
38+
if (im->image[y][x] & mask) { \
39+
has_data = 1; \
40+
bbox[0] = x; \
41+
bbox[1] = y; \
42+
break; \
43+
} \
44+
} \
45+
if (has_data) { \
46+
break; \
47+
} \
48+
} \
49+
/* Check that we have a box */ \
50+
if (bbox[1] < 0) { \
51+
return 0; /* no data */ \
52+
} \
53+
/* second stage: looking for any pixels from bottom */ \
54+
for (y = im->ysize - 1; y >= bbox[1]; y--) { \
55+
has_data = 0; \
56+
for (x = 0; x < im->xsize; x++) { \
57+
if (im->image[y][x] & mask) { \
58+
has_data = 1; \
59+
if (x < bbox[0]) { \
60+
bbox[0] = x; \
61+
} \
62+
bbox[3] = y + 1; \
63+
break; \
64+
} \
65+
} \
66+
if (has_data) { \
67+
break; \
68+
} \
69+
} \
70+
/* third stage: looking for left and right boundaries */ \
71+
for (y = bbox[1]; y < bbox[3]; y++) { \
72+
for (x = 0; x < bbox[0]; x++) { \
73+
if (im->image[y][x] & mask) { \
74+
bbox[0] = x; \
75+
break; \
76+
} \
77+
} \
78+
for (x = im->xsize - 1; x >= bbox[2]; x--) { \
79+
if (im->image[y][x] & mask) { \
80+
bbox[2] = x + 1; \
81+
break; \
82+
} \
83+
} \
5384
}
5485

5586
if (im->image8) {
@@ -71,11 +102,6 @@ ImagingGetBBox(Imaging im, int bbox[4], int alpha_only) {
71102
GETBBOX(image32, mask);
72103
}
73104

74-
/* Check that we got a box */
75-
if (bbox[1] < 0) {
76-
return 0; /* no data */
77-
}
78-
79105
return 1; /* ok */
80106
}
81107

@@ -144,6 +170,9 @@ ImagingGetExtrema(Imaging im, void *extrema) {
144170
imax = in[x];
145171
}
146172
}
173+
if (imin == 0 && imax == 255) {
174+
break;
175+
}
147176
}
148177
((UINT8 *)extrema)[0] = (UINT8)imin;
149178
((UINT8 *)extrema)[1] = (UINT8)imax;

0 commit comments

Comments
 (0)