import cv2
import numpy as np
from time import sleep

Lx=640; Ly=480; F=2; Lx2=int(Lx/F); Ly2=int(Ly/F); XLT=Lx2-100; XRT=Lx2+100
WD=0; F8=2; Lx8=int((Lx-2*WD)/F8); Ly8=int(Ly/F8); MIDX=int(Lx8/2)

########################fbarr
def barrier(PIN,image):
    BLOW=120
    img2 = cv2.resize(image, (Lx8,Ly8), interpolation=cv2.INTER_AREA)
    lower = np.array([PIN[0]-20,PIN[1]-50,120])
    upper = np.array([PIN[0]+20,PIN[1]+50,250])
    lower = np.array(lower, dtype="uint8")
    upper = np.array(upper, dtype="uint8")
    print('lower=',lower,' upper=',upper)
    mask = cv2.inRange(img2, lower, upper)
    hsv=cv2.cvtColor(img2,cv2.COLOR_BGR2HSV)
    pn=100
    for i in range(Lx8):print(i,img2[pn,i,:],hsv[pn,i,:],mask[pn,i],lower,upper)
    cv2.line(img2,(0,pn),(Lx8-1,pn),(255,0,0),2)
    ori=np.copy(img2)
    #img3=mgray(img2,hsv)
    img3=np.copy(img2)
    gray = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY)
    cv2.imshow('gray',gray)
    cv2.imshow('img2',img2)
    cv2.imshow('img3',img3)
    blurred = cv2.GaussianBlur(gray, (5,5), 0)
    binary1 = cv2.Canny(blurred, 40, 150)  #70 shadow
    bb0=np.copy(binary1)
    b0=np.copy(binary1)
    b0[:,b0.shape[1]-4:b0.shape[1]]=100
    thr2=cv2.threshold(gray,30,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)[1]
    ret,thr1=cv2.threshold(gray,BLOW,255,cv2.THRESH_BINARY_INV)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2))
    op1=cv2.morphologyEx(thr1,cv2.MORPH_OPEN,kernel,iterations=3)
    hbin1=np.hstack((b0,op1))
    binaryIMG=np.copy(op1)
    result=cv2.bitwise_and(ori,ori,mask=binaryIMG)
    res2=np.copy(result)
    #cv2.imshow('hbin1',hbin1)
    cv2.imshow('op1',op1)
    cv2.imshow('res2',res2)
    cv2.waitKey(0)
    #return res2,Bdat


def contr(PIN,cap):
    _,image=cap.read()
    lower = [1, 0, 20]
    upper = [60, 40, 220]
    lower = np.array([PIN[0]-30,PIN[1]-50,20])
    upper = np.array([PIN[0]+30,PIN[1]+50,250])
    lower = np.array(lower, dtype="uint8")
    upper = np.array(upper, dtype="uint8")
    mask = cv2.inRange(image, lower, upper)


    output = cv2.bitwise_and(image, image, mask=mask)
    ret,thresh = cv2.threshold(mask, 40, 255, 0)
    #if (cv2.__version__[0] > 3):
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, 
                cv2.CHAIN_APPROX_NONE)
    #else:
    #    im2, contours, hierarchy = cv2.findContours(thresh, 
    #            cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    if len(contours) != 0:
        # draw in blue the contours that were founded
        cv2.drawContours(output, contours, -1, 255, 3)
        # find the biggest countour (c) by the area
        c = max(contours, key = cv2.contourArea)
        x,y,w,h = cv2.boundingRect(c)
        # draw the biggest contour (c) in green
        cv2.rectangle(output,(x,y),(x+w,y+h),(0,255,0),2)
    # show the images
    cv2.imshow("Result", np.hstack([image, output]))
    cv2.imshow('mask',mask)
    cv2.waitKey(0)






def BGR2HSV():
    img2=np.full((200,200,3),0,dtype=np.uint8)
    for j in range(1):
        BGR=input('(BGR='); #G=input('G='); R=input('R=')
        a=BGR.split()
        B=int(a[0]); G=int(a[1]); R=int(a[2])
        img2[:,:]=np.array([B,G,R], dtype=np.uint8)
        hsv = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)
        print('j=',j,img2[0,0],hsv[0,0])
        cv2.imshow('img2',img2)
        cv2.waitKey(0)
        sleep(1)
        cv2.destroyWindow("img2")
        #cv2.destroyWindow('image')
        #cv2.destroyAllWindows()


def HSV2BGR():
    hsv=np.full((200,200,3),0,dtype=np.uint8)
    for j in range(1):
        HSV=input('(HSV='); 
        a=HSV.split()
        H=int(a[0]); S=int(a[1]); V=int(a[2])
        hsv[:,:]=np.array([H,S,V], dtype=np.uint8)
        img2 = cv2.cvtColor(hsv, cv2.COLOR_BGR2HSV)
        print('j=',j,hsv[0,0],img2[0,0])
        cv2.imshow('img2',img2)
        cv2.waitKey(0)
        sleep(1)
        cv2.destroyWindow("img2")
        #cv2.destroyWindow('image')
        #cv2.destroyAllWindows()




def showhsv(pin):
    HSV=np.full((100,100,3),0,dtype=np.uint8)
    for j in range(10):
        H,S,V=pin[0]+3*j,pin[1], pin[2]
        print('j=',j,[H,S,V])
        HSV[:,:]=np.array([H,S,V], dtype=np.uint8)
        IMG = cv2.cvtColor(HSV, cv2.COLOR_HSV2BGR)
        cv2.imshow('IMG',IMG)
        cv2.waitKey(0)
        cv2.destroyWindow('IMG')
        sleep(1)
    input('11111')


def targ(frame,lower,upper):
    hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
    mask=cv2.inRange(hsv,lower,upper)
    res = cv2.bitwise_and(frame,frame,mask= mask)
    #print('lower=',lower,' upper=',upper)
    pn=180
    #for i in range(Lx8):
        #if(mask[pn,i]>10):print(i,frame[pn,i,:],hsv[pn,i,:],mask[pn,i],lower)
        #print(i,frame[pn,i,:],hsv[pn,i,:],mask[pn,i],lower)
    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    #cv2.waitKey(0)
    #cv2.destroyAllWindows()



#--------------- GET PIN color in HSV
def Fcolor(img):
    img2=cv2.resize(img,(80,60))
    hsv=cv2.cvtColor(img2,cv2.COLOR_BGR2HSV)
    PIN=[0,0,0]; PIM=[0,0,0]
    for i in range(3):
        a=int(np.average(img2[30:40,35:45,i]))
        b=int(np.average(hsv[30:40,35:45,i]))
        #print(i,a,b)
        PIM[i]=a; PIN[i]=b
    cv2.circle(img2,(40,35), 5, (255,0,0), 2)
    img4=cv2.resize(img2,(640,480))
    #cv2.imshow('img4',img4)
    #print('PIN_Fcolor_hsv=',PIN)
    #cv2.waitKey(0)
    return PIM,PIN,img4

Lx=320; Ly=240; F=8; Lx2=int(Lx/F); Ly2=int(Ly/F)
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, Lx); cap.set(cv2.CAP_PROP_FRAME_HEIGHT, Ly)
sleep(2)

#----------- Get the HSV_PIN of the target
PIN=[171, 188, 184]
lower = np.array([PIN[0]-30,PIN[1]-50,20])
upper = np.array([PIN[0]+30,PIN[1]+50,250])
lower = np.array([PIN[0]-30,0,0])
upper = np.array([PIN[0]+30,255,255])
lower = np.array(lower, dtype="uint8")
upper = np.array(upper, dtype="uint8")
print('PIN=',PIN,lower,upper)
if(1==1):
    for j in range(16):
        _,image=cap.read()
        PIM,PIN,img4=Fcolor(image)
        print('Fcolor_j=',j,PIM,PIN)
        f='RED_'+str(j)+'.png'
        cv2.imwrite(f,img4)
        cv2.imshow('img4',img4)
        targ(image,lower,upper)
        if cv2.waitKey(1) & 0xFF == ord('q'): break
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    input('1111')
#-----------------------------------------


#contr(PIN,cap)


#-----This part helps us learn the relationship between the two color encodings
if(1==2):
    for j in range(10):
        K=int(input('1=BGR2HSV; 2=HSV2BGR \n K='))
        if(K==1): BGR2HSV()
        if(K==2): HSV2BGR()
    input('BBBBBB')



#lower_blue = np.array([110,50,50])
#lower_blue = np.array([50,50,110])
#upper_blue = np.array([255,255,130])

#PIN=[175,190,130]
#[176, 198, 125]
# PIN_Fcolor_hsv= [176, 233, 113]  21-1A no lamp
#PIN=[176, 233, 113]
PIN=[171, 188, 184]

print('PIN=',PIN)
#lower_red = np.array([PIN[0]-30,PIN[1]-50,PIN[2]-100])
#upper_red = np.array([PIN[0]+30,PIN[1]+50,PIN[2]+100])
lower = np.array([PIN[0]-30,PIN[1]-50,20])
upper = np.array([PIN[0]+30,PIN[1]+50,250])

#contr(PIN,cap)
#_, image=cap.read()
#barrier(PIN,image)
#input('ccccc')


while(1):
    _, frame = cap.read()
    hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
    mask=cv2.inRange(hsv,lower,upper)
    res = cv2.bitwise_and(frame,frame,mask= mask)
    #print('lower=',lower,' upper=',upper)
    pn=180
    for i in range(Lx8):
        if(mask[pn,i]>10):print(i,frame[pn,i,:],hsv[pn,i,:],mask[pn,i],lower)
        #print(i,frame[pn,i,:],hsv[pn,i,:],mask[pn,i],lower)
    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    cv2.waitKey(0)
    k = cv2.waitKey(5) & 0xFF
    if k == 27: break
cv2.destroyAllWindows()


