
##################GET the color code on the bottom line########
def bottclr(img):
    img1=np.copy(img)
    img2=cv2.resize(img1,(160,120))
    hsv=cv2.cvtColor(img2,cv2.COLOR_BGR2HSV)
    Y1=90; Y2=86; Y3=82
    for x in range(160):
        print(x,img2[Y1,x,:],hsv[Y1,x,:],img2[Y2,x,:],hsv[Y2,x,:],
          img2[Y3,x,:],hsv[Y3,x,:])
    cv2.line(img2,(0,Y1),(159,Y1),(0,255,0),1)
    cv2.line(img2,(0,Y2),(159,Y2),(0,255,0),1)
    cv2.line(img2,(0,Y3),(159,Y3),(0,255,0),1)
    img2=cv2.resize(img2,(640,480))
    cv2.imshow('fcolor',img2)
    #cv2.waitKey(0)
    
    
def censcan(img):
    Lx=img.shape[1]; Ly=img.shape[0]
    im1=np.copy(img)
    hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    YC=int(Ly/2); NC=0; NBW=0; NWB=0
    for j in range(1,Lx):
        #print(j,img[YC,j-1,:],hsv[YC,j-1,:],hsv[YC,j,:])
        if(NC>Lx/4): 
            print('NC=',NC);
            return 0
        if(hsv[YC,j-1,1]>40): NC+=1
        if(0<=hsv[YC,j-1,1]<40 and hsv[YC,j-1,2]<40 and hsv[YC,j,2]>150): 
            NBW+=1
            #print('NBW=',NBW,YC,j,(hsv[YC,j-1,2],hsv[YC,j,2]))
            #cv2.circle(im1,(j-1,YC),4,(0,0,255),-1)
        if(0<=hsv[YC,j-1,1]<40 and hsv[YC,j-1,2]>150 and hsv[YC,j,2]<40): 
            NWB+=1  
            #print('NWB=',NWB)
            #cv2.circle(im1,(j-1,YC),6,(0,255,0),-1)
    if(NWB>7 or NBW>7): 
        KC=1; print('NWB,NBW=',NWB,NBW,' KC=',KC)
    else: KC=0    
    #cv2.imshow('im1',im1)
    #cv2.waitKey(0)
    return KC



def tilt(img):
    #print('inside tilt',img.shape)
    Lx=img.shape[1]; Ly=img.shape[0]
    im1=np.copy(img)
    hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    YC=int(Ly/2); NC=0; NBW=0; NWB=0; X=[]
    for i in range(Ly):
        for j in range(1,int(Lx/3)):
            DD=int(hsv[i,j,2])-int(hsv[i,j-1,2])
            #if(i==YC): print(i,j,hsv[i,j-1,:],hsv[i,j,:],DD,NBW)
            if(0<=hsv[i,j-1,1]<40 and hsv[i,j,2]>160 and DD>40): 
                NBW+=1;  #print('NBW=',NBW,i,j);
                if(NBW==1): x1=j; X.append([j,i]); continue
                if(NBW>1 and abs(j-x1)<10): X.append([j,i]); cv2.circle(im1,(j-1,i),4,(0,0,255),-1); break
                else: x1=j               
    cv2.imshow('im1',im1)
    print('X=',X)
    p1=X[0]; p2=[Lx,0]; p3=X[-1]
    q3=p3; q2=p2; q1=[p3[0],0];
    print(p1,p2,p3); print(q1,q2,q3)
    rows,cols,ch = img.shape
    #print('rows:',rows,cols,ch)
    pts1 = np.float32([p1,p2,p3])
    pts2 = np.float32([q1,q2,q3])
    M = cv2.getAffineTransform(pts1,pts2)
    #print('type(M)',type(M),M.shape,M)
    imgTL=cv2.warpAffine(img,M,(cols,rows)) 
    #cv2.imshow('imgTL',imgTL)
    #cv2.waitKey(0)
    return imgTL


    
def tarbox(image):
    Lx=image.shape[1]; Ly=image.shape[0];
    Lxg=Lx; Lyg=Ly; Fg=1
    img2 = cv2.resize(image, (Lxg,Lyg), interpolation=cv2.INTER_AREA)
    img1=np.copy(image)
    img2=np.copy(image)
    gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    cnts1,_ = cv2.findContours(gray.copy(), cv2.RETR_EXTERNAL,
          cv2.CHAIN_APPROX_SIMPLE) # cv2.RETR_LIST
    lcnts1=len(cnts1); 
    #print('lcnts1=',lcnts1)
    N1=0; ax=0; cx=0; px=0; mx1=0; Kc1=0; xx1=[0 for i in range(5)]
    clone1=img2.copy(); data1=[]
    for c in cnts1:
        M=cv2.moments(c)
        if(M['m00']==0): M['m00']=1
        cX=int(M['m10']/M['m00']); cY=int(M['m01']/M['m00'])
        area = cv2.contourArea(c); area3=round(area,3); #print(j,area3)
        area=int(area)
        (x,y,w,h)=cv2.boundingRect(c); Ac=w*h; asp=round(h/w,2)        
        if(Ac<2000*4 or Ac>8000*12): continue
        if(asp>0.7 or asp<0.4): continue
        if(area<10000): continue
        imgc=img1[y:y+h,x:x+w,:]
        KC=censcan(imgc)
        if(KC==0): 
            cv2.rectangle(clone1,(x,y),(x+w,y+h),(0,0,255),8)
            continue
        Kc1=1; N1+=1; 
        xx1=(x,y,w,h); mx1=(cX,cY)
        d=[Ac,xx1,mx1]; data1.append(d)
        print(N1,xx1,area,Ac,asp,KC)
        cv2.circle(clone1,mx1,6,(0,125,255),-1)
        x,y,w,h=xx1[0],xx1[1],xx1[2],xx1[3]
        cv2.rectangle(clone1,(x,y),(x+w,y+h),(255,125,0),8)
        #cv2.imshow('tarbox',clone1)    
    lenda=len(data1)
    print('N1=',N1,lenda,data1)
    #cv2.waitKey(0)
    return lenda,data1,clone1


def whitebox(image):
    #---------------------------- white color----------
    low=np.array([10,0 ,150 ])
    upp=np.array([250,40 ,255 ])
    #img=cv2.resize(image,(640,480))
    img=cv2.resize(image,(1280*2,960*2))
    hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    mask1=cv2.inRange(hsv,low,upp)
    imgmask=cv2.bitwise_and(img,img,mask=mask1)
    img3=np.copy(imgmask)
    #img3=cv2.resize(imgmask,(640,480))
    lenda,data1,imgt=tarbox(img3)
    imgts=cv2.resize(imgt,(1280,960))
    print('imgt.shape=',imgt.shape)
    #cv2.imshow('mask1',mask1)
    cv2.imshow('imgts',imgts)
    blue=[]; 
    if(lenda>0):
        for i in range(lenda):
            (x,y,w,h)=data1[i][1]
            imgi=img3[y:y+h,x:x+w,:]
            imgi=img[y:y+h,x:x+w,:]
            imgir=cv2.resize(imgi,(128,128))
            imgTL=tilt(imgi)
            cv2.imshow('tar_'+str(i),imgTL)
            cv2.waitKey(0)
            blue.append(imgTL)
    #return lenda,data1,imgt,blue



if __name__ == '__main__':
    from time import sleep
    import cv2
    import numpy as np
    print('fcolor.py as a main')
    low=np.array([10,0 ,150 ])
    upp=np.array([250,40 ,255 ])
    PIC=['P2.JPG','P3.JPG','P4.JPG','P5.JPG','P6.JPG']
    for j in range(4,5):
        #ret,img=cap.read()
        #if(j==0): fn='P2A.png'
        #if(j==0): fn='P2.JPG'
        #if(j==1): fn='P3.JPG'
        fn=PIC[j]
        imgi=cv2.imread(fn)
        #print('imgi.shape=',imgi.shape)
        #bottclr(imgi)
        whitebox(imgi)
        #if cv2.waitKey(1) & 0xFF == ord('q'): break
        cv2.waitKey(0)

