# -*- coding: iso-8859-15 -*-

import numpy as np
import cv2


class TheSquaire:
    
    def rechtecke(self,src=None,th=200,minarea=30000,maxarea=185000):
        
        attributes=np.empty((50),dtype=object)

        conties=np.empty((50),dtype=object)

        #blank=np.zeros((512,576,1),dtype=np.uint8)

        retval , binary = cv2.threshold(src, th, 255, cv2.THRESH_BINARY_INV)

        bin, cont , hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

        i=0
        
        for  cnt in cont:
            
            cnt_len = cv2.arcLength(cnt, True)

            cnt = cv2.approxPolyDP(cnt, 0.03*cnt_len, True)

            #cnt=cv2.convexHull(cnt)
            ar=np.uint32(cv2.contourArea(cnt))
            
            if len(cnt)>3 and len(cnt)<7 and ar>minarea and ar<maxarea:

                rect=cv2.minAreaRect(cnt)

                box=np.int0(cv2.boxPoints(rect))

                conties[i]=box
                attributes[i]=ar
                i+=1


        return(conties[0:i:1])

    #per referenz einfügen: zeichne_rechtecke(rechtecke,[ursprungsbild]/[maskenrohling])

    def zeichne_rechtecke(self,r,dst=None,masking=True,mask=None):
            if masking:
                cv2.drawContours( mask[0], r, -1, 255, -1 )
                #mask[0] = cv2.erode(mask[0], np.ones((21,21),np.uint8))
            else:
                cv2.drawContours( dst[0], r, -1, 128, 5 )


    def kreise(self,x):

        frame,minr,maxr,accres,uppercanny,thres= x[0],x[1],x[2],x[3],x[4],x[5]

        
        
        circles = cv2.HoughCircles(frame, cv2.HOUGH_GRADIENT, dp=accres, minDist=30,param1=uppercanny,param2=thres,maxRadius=maxr,minRadius=minr)


        if circles is not None:

                circles=np.round(circles[0,:]).astype("int")

                
                
        return circles

    #per referenz einfügen: zeichne_kreise(result,[ursprungsbild])

##    def zeichne_kreise(self,result,dst):
##        for arr in result:
##            if arr is not None:
##                for circ in arr.tolist():
##                    (x,y,r)=circ
##                    cv2.circle(dst[0],(x,y),r,(0,255,0),4)
##                    cv2.rectangle(dst[0],(x-5,y-5),(x+5,y+5),(0,128,255),-1)
##                    cv2.line(dst[0],(400,304),(x,y),(0,0,255),3)
        
    def zeichne_kreise(self,result,dst):
        if result is not None:
                for (x,y,r) in result:
                    cv2.circle(dst[0],(x,y),r,(0,200,0),4)
                    cv2.rectangle(dst[0],(x-5,y-5),(x+5,y+5),(0,128,255),-1)
                    cv2.line(dst[0],(287,255),(x,y),(0,0,255),3)
