Skip to content

Instantly share code, notes, and snippets.

@mgranberry
Last active September 6, 2016 21:21
Show Gist options
  • Save mgranberry/bc8d365d68737b0093d14a61885f2feb to your computer and use it in GitHub Desktop.
Save mgranberry/bc8d365d68737b0093d14a61885f2feb to your computer and use it in GitHub Desktop.
Take the input image (a button on a white background), calculate an ellipse bounding the button, crop the bounded ellipse, and write out the image.
import numpy as np
import cv2
im = cv2.imread('button1.jpg')
hsv_img = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
kernel = np.ones((5,5),np.uint8)
edges = cv2.morphologyEx(hsv_img, cv2.MORPH_GRADIENT, kernel)
ret, thresh = cv2.threshold(edges,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
cv2.imshow("Show", thresh)
cv2.waitKey()
cv2.destroyAllWindows()
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# hulls = [cv2.convexHull(cnt) for cnt in contours]
hulls = contours
ellipses = [cv2.fitEllipse(hull) for hull in hulls if len(hull) >=5]
# for ellipse in ellipses:
# cv2.ellipse(im, ellipse, (0, 255, 0), 2)
big_ellipse = max(ellipses, key=lambda x: x[1])
print big_ellipse
im2 = im.copy()
cv2.ellipse(im2, big_ellipse, (0, 255, 0), 2)
cv2.imshow('Show', im2)
cv2.waitKey()
x_center, y_center, ell_w, ell_h = big_ellipse[0][1], big_ellipse[0][0], big_ellipse[1][1], big_ellipse[1][0]
x1 = x_center - ell_w // 2
y1 = y_center - ell_h // 2
im = im[x1:x1 + int(ell_w), y1:y1 + int(ell_h)]
cv2.imwrite('cropped_button.jpg', im)
cv2.imshow('Show', im)
cv2.waitKey()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment