from IPython.core.display import Image Image(filename='001/eye-diagram.jpg') %matplotlib inline import cv2 import numpy as np import matplotlib.pyplot as plt image = cv2.imread('001/eye.png') gray = cv2.cvtColor(image, cv2.cv.CV_BGR2GRAY) plt.figure(figsize=(10, 5)) plt.imshow(gray, cmap='gray') retval, thresholded = cv2.threshold(gray, 30, 255, cv2.cv.CV_THRESH_BINARY) plt.figure(figsize=(10, 5)) plt.imshow(thresholded, cmap='gray') kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 10)) closed = cv2.erode(cv2.dilate(thresholded, kernel, iterations=1), kernel, iterations=1) plt.figure(figsize=(10, 5)) plt.imshow(closed, cmap='gray') contours, hierarchy = cv2.findContours(closed, cv2.cv.CV_RETR_LIST, cv2.cv.CV_CHAIN_APPROX_NONE) drawing = np.copy(image) for contour in contours: area = cv2.contourArea(contour) bounding_box = cv2.boundingRect(contour) extend = area / (bounding_box[2] * bounding_box[3]) # reject the contours with big extend if extend > 0.8: continue # calculate countour center and draw a dot there m = cv2.moments(contour) if m['m00'] != 0: center = (int(m['m10'] / m['m00']), int(m['m01'] / m['m00'])) cv2.circle(drawing, center, 3, (0, 255, 0), -1) # fit an ellipse around the contour and draw it into the image ellipse = cv2.fitEllipse(contour) cv2.ellipse(drawing, box=ellipse, color=(0, 255, 0)) plt.figure(figsize=(10, 5)) plt.imshow(drawing)