Skip to content

Instantly share code, notes, and snippets.

@notnotrishi
Last active July 23, 2025 00:21
Show Gist options
  • Select an option

  • Save notnotrishi/4e46ed203208296879e57bf465f5b2ac to your computer and use it in GitHub Desktop.

Select an option

Save notnotrishi/4e46ed203208296879e57bf465f5b2ac to your computer and use it in GitHub Desktop.
Estimate corner radius
# This function estimates the corner radius of a window by checking multiple directions from each corner
# and finding the distance where the image changes from transparent to solid.
# It’s useful for detecting rounded corners in screenshots of macOS windows or pixel data of images etc.
def estimate_corner_radius(self, image_or_array, threshold=128, samples=8):
import math
import numpy as np
# if input is a PIL Image, convert to numpy array
if hasattr(image_or_array, 'convert'):
arr = np.asarray(image_or_array.convert("RGBA"))
else:
arr = image_or_array
height, width, _ = arr.shape
max_radius = min(width, height) // 4
corner_data = [((1, 1), 0),
((width - 2, 1), 90),
((1, height - 2), 270),
((width - 2, height - 2), 180),
]
angle_offsets = np.linspace(0, 90, samples, endpoint=False)
def _estimate_corner(corner, base_angle):
cx, cy = corner
radii = []
for angle in angle_offsets + base_angle:
rad = math.radians(angle)
dx, dy = math.cos(rad), math.sin(rad)
for r in range(1, max_radius):
x = int(round(cx + r * dx))
y = int(round(cy + r * dy))
if not (0 <= x < width and 0 <= y < height):
break
alpha = arr[y, x, 3]
if alpha >= threshold:
radii.append(r)
break
return min(radii) if radii else max_radius
corner_radii = [_estimate_corner(corner, angle) for corner, angle in corner_data]
valid_radii = [r for r in corner_radii if r > 0]
estimated_radius = min(valid_radii) if valid_radii else 0
return max(0, estimated_radius)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment