Skip to content

Commit

Permalink
Improve efficiency when a radius is zero
Browse files Browse the repository at this point in the history
  • Loading branch information
radarhere committed Aug 12, 2023
1 parent c167d7a commit 0aea242
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 17 deletions.
4 changes: 4 additions & 0 deletions src/PIL/ImageFilter.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ def filter(self, image):
xy = self.radius
if not isinstance(xy, (tuple, list)):
xy = (xy, xy)
if xy == (0, 0):
return image.copy()

Check warning on line 174 in src/PIL/ImageFilter.py

View check run for this annotation

Codecov / codecov/patch

src/PIL/ImageFilter.py#L174

Added line #L174 was not covered by tests
return image.gaussian_blur(xy)


Expand Down Expand Up @@ -202,6 +204,8 @@ def filter(self, image):
xy = self.radius
if not isinstance(xy, (tuple, list)):
xy = (xy, xy)
if xy == (0, 0):
return image.copy()
return image.box_blur(xy)


Expand Down
42 changes: 25 additions & 17 deletions src/libImaging/BoxBlur.c
Original file line number Diff line number Diff line change
Expand Up @@ -258,29 +258,37 @@ ImagingBoxBlur(Imaging imOut, Imaging imIn, float xradius, float yradius, int n)
return ImagingError_ModeError();
}

imTransposed = ImagingNewDirty(imIn->mode, imIn->ysize, imIn->xsize);
if (!imTransposed) {
return NULL;
}

/* Apply blur in one dimension.
Use imOut as a destination at first pass,
then use imOut as a source too. */
ImagingHorizontalBoxBlur(imOut, imIn, xradius);
for (i = 1; i < n; i++) {
ImagingHorizontalBoxBlur(imOut, imOut, xradius);
}
/* Transpose result for blur in another direction. */
ImagingTranspose(imTransposed, imOut);

/* Reuse imTransposed as a source and destination there. */
for (i = 0; i < n; i++) {
ImagingHorizontalBoxBlur(imTransposed, imTransposed, yradius);
if (xradius != 0) {
ImagingHorizontalBoxBlur(imOut, imIn, xradius);
for (i = 1; i < n; i++) {
ImagingHorizontalBoxBlur(imOut, imOut, xradius);
}
}
/* Restore original orientation. */
ImagingTranspose(imOut, imTransposed);
if (yradius != 0) {
imTransposed = ImagingNewDirty(imIn->mode, imIn->ysize, imIn->xsize);
if (!imTransposed) {
return NULL;

Check warning on line 274 in src/libImaging/BoxBlur.c

View check run for this annotation

Codecov / codecov/patch

src/libImaging/BoxBlur.c#L274

Added line #L274 was not covered by tests
}

ImagingDelete(imTransposed);
/* Transpose result for blur in another direction. */
ImagingTranspose(imTransposed, xradius == 0 ? imIn : imOut);

/* Reuse imTransposed as a source and destination there. */
for (i = 0; i < n; i++) {
ImagingHorizontalBoxBlur(imTransposed, imTransposed, yradius);
}
/* Restore original orientation. */
ImagingTranspose(imOut, imTransposed);

ImagingDelete(imTransposed);
}
if (xradius == 0 && yradius == 0) {
ImagingCopy2(imOut, imIn);
}

return imOut;
}
Expand Down

0 comments on commit 0aea242

Please sign in to comment.