# -*- coding: utf-8 -*-
"""
"""
import cv2
import numpy as np
from matplotlib import pyplot as plt
from preproces_max import *


img_num = 102562
#
#img = cv2.imread('images_test_rev1/'+str(img_num)+'.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
#(thresh, im_bw) = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
#
#img_num = 101468
per = 80#%


img = cv2.imread('images_test_rev1/'+str(img_num)+'.jpg', 0)
tt = int((per/100.0)*max_img(img))
print tt
ret,thresh = cv2.threshold(img,tt,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)
contours,hierarchy = cv2.findContours(thresh, 1, 2)
#contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#Max Area contour
cnt,mm=0,0
for c in contours:
    if mm < cv2.contourArea(c):
        mm = cv2.contourArea(c)
        cnt = c

img = cv2.imread('images_test_rev1/'+str(img_num)+'.jpg')
#cv2.drawContours(img,contours,-1,(0,255,0),3)

#(x,y),radius = cv2.minEnclosingCircle(cnt)
#center = (int(x),int(y))
#radius = int(radius)
#img = cv2.circle(img,center,radius,(0,255,0),2)
ellipse = cv2.fitEllipse(cnt)
#print ellipse
cv2.ellipse(img, ellipse,(0,255,0),3)
#print img
#cv2.drawContours(img,contours,-1,(0,255,0),3)
print len(contours)

plt.subplot(1,1,1),plt.imshow(img)
plt.title('Ellipse Fit')
plt.axis('off')