import cv2
import numpy as np




def getcontours(img,cThr=[100,100],showCanny=False,minArea=1000,filter=0,draw = False):
    imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    imgBlur = cv2.GaussianBlur(imgGray,(5,5),1)
    imgCanny = cv2.Canny(imgBlur,cThr[0],cThr[1])
    kernel = np.ones((5,5))
    imgDial = cv2.dilate(imgCanny,kernel,iterations=3)
    imgThre = cv2.erode(imgDial,kernel,iterations=2)

    if showCanny:
        #imgThre = cv2.resize(imgThre, (0, 0), None, 0.3, 0.3)
        cv2.imshow('Canny',imgThre)
        contours,hiarchy =  cv2.findContours(imgThre,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
        finalContours=[]

        for i in contours:
            area = cv2.contourArea(i)
            if area > minArea:
                per = cv2.arcLength(i,True)
                approx = cv2.approxPolyDP(i,0.02*per,True)
                bb0x = cv2.boundingRect(approx)
                if filter>0:
                    if len(approx) == filter:
                        finalContours.append([len(approx),area,approx,bb0x,i])
                else:
                    finalContours.append([len(approx), area, approx, bb0x, i])

        finalContours = sorted(finalContours,key=lambda x:x[1],reverse=True)
        if draw:
            for con in finalContours:
                cv2.drawContours(img,con[4],-1,(0,0,255),3)
        return img, finalContours

def reorder(myPoints):
    print(myPoints.shape)
    myPointsnew = np.zeros_like(myPoints)
    myPoints = myPoints.reshape((4,2))
    add = myPoints.sum(1)
    myPointsnew[0] = myPoints[np.argmin(add)]
    myPointsnew[3] = myPoints[np.argmax(add)]
    dif = np.diff(myPoints,axis=1)
    myPointsnew[1] = myPoints[np.argmin(dif)]
    myPointsnew[2] = myPoints[np.argmax(dif)]
    return myPointsnew


def warpImg(img,points,w,h,pad=20):
   # print(points)
    points = reorder(points)

    pt1 = np.float32(points)
    pt2 = np.float32([[0,0],[w,0],[0,h],[w,h]])
    matrix = cv2.getPerspectiveTransform(pt1,pt2)
    imgWarp = cv2.warpPerspective(img,matrix,(w,h))
    imgWarp = imgWarp[pad:imgWarp.shape[0]-pad, pad: imgWarp.shape[1]-pad]
    return imgWarp


def findDistance(pt1,pt2):
    return ((pt2[0]-pt1[0])**2 + (pt2[1]-pt1[1])**2)**0.5


