Skip to content

Commit

Permalink
Optimized Box Blur for different x-y radii (#2795)
Browse files Browse the repository at this point in the history
  • Loading branch information
RunDevelopment authored Apr 15, 2024
1 parent bff4938 commit 60a0bb5
Showing 1 changed file with 21 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,15 @@ def box_blur_node(
radius_x: float,
radius_y: float,
) -> np.ndarray:
if radius_x == 0 or radius_y == 0:
if radius_x == 0 and radius_y == 0:
return img

use_optimized_int = (
# both radii are integers
int(radius_x) == radius_x
and int(radius_y) == radius_y
# you can't tell the difference between a float and an integer when the radius is large enough
or radius_x > 200
and radius_y > 200
)
# you can't tell the difference between a float and an integer when the radius is large enough
radius_x = round(radius_x) if radius_x > 200 else radius_x
radius_y = round(radius_y) if radius_y > 200 else radius_y

# both radii are integers
use_optimized_int = int(radius_x) == radius_x and int(radius_y) == radius_y

if use_optimized_int:
# we can use an optimized box blur implementation
Expand All @@ -103,6 +101,20 @@ def box_blur_node(
img, (radius_x * 2 + 1, radius_y * 2 + 1), borderType=cv2.BORDER_REFLECT_101
)

# cv2.blur is so much faster than the other methods, that it's worth manually separating the kernel.
# the idea here is that we blur with cv2.blur in x or y if we can
threshold = 15
if radius_x >= threshold and int(radius_x) == radius_x:
img = cv2.blur(
img, (int(radius_x) * 2 + 1, 1), borderType=cv2.BORDER_REFLECT_101
)
radius_x = 1
if radius_y >= threshold and int(radius_y) == radius_y:
img = cv2.blur(
img, (1, int(radius_y) * 2 + 1), borderType=cv2.BORDER_REFLECT_101
)
radius_y = 1

# Separable filter is faster for relatively small kernels, but after a certain size it becomes
# slower than filter2D's DFT implementation. The exact cutoff depends on the hardware.
avg_radius = math.sqrt(radius_x * radius_y)
Expand Down

0 comments on commit 60a0bb5

Please sign in to comment.