Difficulty detecting object shape change between good and bad states using fitEllipse and convex hull in OpenCV

69 Views Asked by At

I'm currently working on a computer vision project where I need to detect changes in the shape of an object, specifically an ellipse, between good and bad states.

I've attempted to use OpenCV's fitEllipse and convex hull methods, but they haven't provided the desired results.

What I'm Looking For:

I'm seeking advice on improving the accuracy of shape detection for an ellipse between good and bad states. Any alternative approaches or libraries that might be better suited for this task.

My code:

import cv2
import numpy as np

# Specify the path to the single image
image_path = "good.jpg"

# Load image
img = cv2.imread(image_path)

# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply a Gaussian blur to reduce noise and improve contour detection
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

edges = cv2.Canny(blurred, 50, 150)

cv2.imshow("Edges", edges)

# Find contours
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

largest_contour = max(contours, key=cv2.contourArea)

cv2.drawContours(img, contours, -1, (0, 255, 0), 2)

# Create an image to draw the convex hull
convex_hull_img = np.zeros_like(img)

# Draw convex hull for the largest contour
hull = cv2.convexHull(largest_contour)

# Fit an ellipse to the convex hull
ellipse = cv2.fitEllipse(hull)

# Calculate the aspect ratio of the fitted ellipse
aspect_ratio = ellipse[1][0] / ellipse[1][1]

print(f"Aspect Ratio: {aspect_ratio}")
cv2.drawContours(convex_hull_img, [hull], -1, (0, 255, 0), 2)
cv2.imshow("convex", convex_hull_img)

# Display the result
cv2.imshow("Original Image", img)

cv2.waitKey(0)
cv2.destroyAllWindows()

I hereby attach images of the ellipse for better understanding of my question good_ellipse bad_ellipse Thank you in advance for your help!

0

There are 0 best solutions below