Skip to content

Instantly share code, notes, and snippets.

@diegoaguilar
Created April 14, 2015 22:03
Show Gist options
  • Save diegoaguilar/cb008e2a6037b3a71c1a to your computer and use it in GitHub Desktop.
Save diegoaguilar/cb008e2a6037b3a71c1a to your computer and use it in GitHub Desktop.
from cv2 import *
bottle_image_name = 'bottle.jpg'
bottle_image = imread(bottle_image_name,CV_LOAD_IMAGE_GRAYSCALE)
contours, hierarchy = findContours(bottle_image, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE)
print contours
for contour in contours:
num_points = len(contour)
if num_points < 5:
print 'upp'# The contour has too few points to fit an ellipse. Skip it.
continue
# We could use area to help determine the type of object.
# Small contours are probably false detections (not really a whole object).
area = contourArea(contour)
bounding_ellipse = fitEllipse(contour)
center, radii, angle_degrees = bounding_ellipse
print center, radii, angle_degrees
# Let's define an ellipse's normal orientation to be landscape (width > height).
# We must ensure that the ellipse's measurements match this orientation.
if radii[0] < radii[1]:
radii = (radii[1], radii[0])
angle_degrees -= 90.0
# We could use the angle to help determine the type of object.
# A bottle or can's angle is probably approximately a multiple of 90 degrees,
# assuming that it is at rest and not falling.
# Calculate the aspect ratio (width / height).
# For example, 0.5 means the object's height is 2 times its width.
# A bottle is probably taller than a can.
aspect_ratio = radii[0] / radii[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment