import cv2
import numpy as np
from imutils.video.pivideostream import PiVideoStream
from time import sleep

def nothing(x):
    pass

print("[INFO] sampling THREADED frames from `picamera` module...")
vs = PiVideoStream((500,500),12).start()
sleep(2)
cv2.namedWindow("detection", cv2.WINDOW_AUTOSIZE)
cv2.createTrackbar('min','detection',80,255,nothing)
cv2.createTrackbar('max','detection',160,255,nothing)
cv2.createTrackbar('grad','detection',0,1,nothing)
cv2.createTrackbar('radres','detection',1,100,nothing)
cv2.createTrackbar('thetares','detection',30,180,nothing)
cv2.createTrackbar('thres','detection',1000,1000,nothing)
cv2.createTrackbar('minlinegap','detection',0,1000,nothing)
cv2.createTrackbar('maxlinegap','detection',10,1000,nothing)
#output=np.zeros((500,500,3),np.uint8)
while cv2.waitKey(1) != ord("q"):
    mi=cv2.getTrackbarPos('min','detection')
    ma=cv2.getTrackbarPos('max','detection')
    grad=cv2.getTrackbarPos('grad','detection')
    radres=cv2.getTrackbarPos('radres','detection')
    thetares=cv2.getTrackbarPos('thetares','detection')*np.pi/180
    thres=cv2.getTrackbarPos('thres','detection')
    minlength=cv2.getTrackbarPos('minlinelength','detection')
    maxgap=cv2.getTrackbarPos('maxlinegap','detection')
    src=vs.read()
    output=src.copy()
    grau = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    srcc = cv2.Canny(grau, mi, ma,L2gradient=grad)
    cv2.imshow('cannyboy',srcc)
##    lines=cv2.HoughLines(srcc,radres,thetares,thres)
##    
##    if lines is not None:
##
##        for line in lines:
##            p,t=line[0]
##
##            a=np.cos(t)
##            b=np.sin(t)
##            xo,yo=a*p,b*p
##            p1=(int(xo-1000*b),int(yo+1000*a))
##            p2=(int(xo+1000*b),int(yo-1000*a))
##            cv2.line(output,p1,p2,(0,0,255),1)
##    cv2.imshow('detection',output)

    x,y=[],[]
    lines=cv2.HoughLinesP(srcc,radres,thetares,thres,minlength,maxgap)
    if lines is not None:
        for l in lines:
            x.append(l[0][0])
            y.append(l[0][1])
            x.append(l[0][2])
            y.append(l[0][3])
            #cv2.line(output,(l[0][0],l[0][1]),(l[0][2],l[0][3]),(0,0,255),1)
        #cv2.rectangle(output,(min(x),min(y)),(max(x),max(y)),(0,255,0),2)
        cv2.imshow('cut',cv2.Canny(output[min(y)+10:max(y)-10,min(x)+10:max(x)-10], mi, ma,L2gradient=grad))
    #cv2.imshow('detection',output)
    
    
cv2.destroyAllWindows()
vs.stop()
