Last active
March 13, 2025 05:13
-
-
Save grandinquisitor/804c61cc75e85f5d2f5297dfca83a0d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SmartCropper: | |
"""Smart cropper that uses a saliency map to determine the most interesting point in an image.""" | |
def __init__(self): | |
# Initialize the saliency detector (using the spectral residual method) | |
try: | |
self.saliency = cv2.saliency.StaticSaliencySpectralResidual_create() | |
except AttributeError: | |
print("run `pip install opencv_contrib_python`") | |
raise | |
def find_interesting_centroid(self, image_path): | |
""" | |
Analyze an image using a saliency map and return the centroid of the most salient region. | |
Args: | |
image_path: Path to the image file. | |
Returns: | |
tuple: (x_percent, y_percent) coordinates of the most interesting point as percentages. | |
""" | |
img = cv2.imread(str(image_path)) | |
if img is None: | |
print(f"Error: Cannot read image at {image_path}") | |
return None | |
# Compute the saliency map | |
success, saliencyMap = self.saliency.computeSaliency(img) | |
if not success: | |
print("Error: Saliency computation failed") | |
return None | |
saliencyMap = (saliencyMap * 255).astype("uint8") | |
# Calculate image moments of the saliency map to determine the centroid | |
moments = cv2.moments(saliencyMap) | |
if moments["m00"] != 0: | |
cX = int(moments["m10"] / moments["m00"]) | |
cY = int(moments["m01"] / moments["m00"]) | |
else: | |
# Fall back to the image center if moments are zero | |
cX, cY = img.shape[1] // 2, img.shape[0] // 2 | |
centroid_x_percent = (cX / img.shape[1]) * 100.0 | |
centroid_y_percent = (cY / img.shape[0]) * 100.0 | |
return centroid_x_percent, centroid_y_percent |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment