Created
April 19, 2015 10:13
-
-
Save diegoaguilar/a4d9a4528bc6faa79113 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
from cv2 import * | |
import sys | |
bottle_image_name = sys.argv[1] | |
bottle_image_gray = imread(bottle_image_name,CV_LOAD_IMAGE_GRAYSCALE) | |
(tresh, im_bw) = threshold(bottle_image_gray, 127, 255, THRESH_BINARY) | |
imwrite('bw.png',im_bw) | |
bottle_image_bw = imread('bw.png',CV_LOAD_IMAGE_UNCHANGED) | |
contours, hierarchy = findContours(bottle_image_bw, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE) | |
aspect_ratios = [] | |
centroids = [] | |
for contour in contours: | |
num_points = len(contour) | |
if num_points < 5: | |
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] | |
aspect_ratios.append(aspect_ratio) | |
m = moments(contour) | |
m00 = m['m00'] | |
m01 = m['m01'] | |
m10 = m['m10'] | |
try: | |
centroid = (m10 / m00, m01 / m00) | |
print centroid | |
except: | |
print("Tried to divide by zero") | |
print sum(aspect_ratios) / float(len(aspect_ratios)) | |
imshow("Pic",bottle_image_bw) | |
waitKey(0) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment