Created
December 25, 2024 14:44
-
-
Save davidsan/c165e36a8d5b72d4b242470c555f22e4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import cv2 | |
def count_curtain_hooks(image_path): | |
# Load and check image | |
image = cv2.imread(image_path) | |
if image is None: | |
raise ValueError("Could not load image.") | |
# Preprocessing: Convert to grayscale, apply Gaussian blur, and detect edges | |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
blurred = cv2.GaussianBlur(gray, (5, 5), 0) | |
edges = cv2.Canny(blurred, 30, 80) | |
# Find contours and filter based on area | |
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
min_contour_area = 200 # Adjust based on hook size | |
filtered_contours = [contour for contour in contours if cv2.contourArea(contour) > min_contour_area] | |
# Create debug image with all contours (before filtering) | |
debug_image = image.copy() | |
cv2.drawContours(debug_image, contours, -1, (255, 0, 0), 1) | |
cv2.imshow("All Contours (Before Filtering)", debug_image) | |
# Draw filtered contours with labels on the result image | |
result_image = image.copy() | |
for i, contour in enumerate(filtered_contours): | |
# Draw contour and label it with the index | |
cv2.drawContours(result_image, [contour], -1, (0, 255, 0), 2) | |
M = cv2.moments(contour) | |
cX = int(M["m10"] / M["m00"]) if M["m00"] != 0 else 0 | |
cY = int(M["m01"] / M["m00"]) if M["m00"] != 0 else 0 | |
cv2.putText(result_image, str(i + 1), (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), 5) | |
# Display result | |
cv2.imshow("Labeled Hooks", result_image) | |
cv2.waitKey(0) | |
cv2.destroyAllWindows() | |
return len(filtered_contours) | |
# Example usage | |
image_path = "curtain_hooks.jpg" | |
num_hooks = count_curtain_hooks(image_path) | |
print(f"Number of hooks detected: {num_hooks}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment