import cv2
import numpy as np
#import matplotlib.pyplot as plt
import time
t0=time.time()

def words(image):
    #自動閥值二值化
    ret,thresh1 = cv2.threshold(image,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

    h=thresh1.shape[1]
    w=thresh1.shape[0]

    # plt.figure()
    # plt.imshow(thresh1)

    #取Y方向波
    y_thresh1=np.zeros([36]).astype('int')
    count_y=0
    for i in range(w):
        for j in range(h):
            if thresh1[i,j]==255:
                y_thresh1[i]+=1    
                count_y+=1



    #投影 Y 軸影像
    y_fig=np.zeros([36,136])

    for i in range(w):
        for j in range(h-y_thresh1[i],h):
            y_fig[i,j]=1


#     plt.figure()
#     plt.imshow(y_fig)

    #Y方向找點
    Q1_y=136-(count_y//36)//2
    def find_ypoint():        
        pos=[w,0]
        bestP=[[],[]]        
        for i in range(w//2,0,-1):       
            if y_fig[i,Q1_y]==0:         #StartPos 找波型於第 Q1_y rol 上
                bestP[0].append(i)          #之 pixel為 0 的位置                  

            if y_fig[w-i,Q1_y]==0 : #EndPos 找波型於第 Q1_y rol 上
                bestP[1].append(w-i)        #之 pixel為 0 的位置                                                          

            if bestP[0] and bestP[1]:
                pos[1]=bestP[0][0]
                pos[0]=bestP[1][0]
                break;
            elif bestP[0]:
                pos[1]=bestP[0][0]
            elif bestP[1]:
                pos[0]=bestP[1][0]

        return pos[1],pos[0]

    #上下精定位車牌位置
    s,e = find_ypoint()


    print("上下定位擷取cols",s,"~",e)

    newImg=np.zeros([(e-s)+1,136])

    for i in range(s,e):
        for j in range(newImg.shape[1]):
            newImg[i-s,j]=thresh1[i,j]

#     plt.figure()
#     plt.imshow(newImg)



    #取X方向波
    h=newImg.shape[1]
    w=newImg.shape[0]
    x_thresh1=np.zeros([136]).astype('int')
    for i in range(h):
         for j in range(w):
            if newImg[j,i]==255:
                x_thresh1[i]+=1            


    #投影 X 軸影像
    x_fig=np.zeros([w,h])

    for i in range(h):
        for j in range(w-x_thresh1[i],w):
            x_fig[j,i]=1
            if i == 0 or i==h:  #前後預留白邊
                x_fig[j,i]=1
            
    # 形態 開 運算
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(6, 6))
    x_fig = cv2.morphologyEx(x_fig, cv2.MORPH_OPEN, kernel)

    #plt.figure()
    #plt.imshow(x_fig)
            
    #左右精定位車牌位置
    def findXrange(x_fig):
        bestP=[[],[]]
        w=x_fig.shape[0]
        for i in range(h):       
            if x_fig[w-1,i]==0:
                bestP[0].append(i)               
            if x_fig[w-1,h-i-1]==0:                
                bestP[1].append(h-i-1)
            if bestP[0] and bestP[1]:               
                return bestP[0][0],bestP[1][0]
            
                
    leftP,rightP=findXrange(x_fig)        #找到左右起始點
    
    print("左右定位擷取 rols",leftP,"~",rightP)
    
    x_fig1=np.zeros([(e-s)+1,(rightP-leftP)+1])   #精定位後的重新投影
    for i in range(leftP,rightP):         
        for j in range(x_fig1.shape[0]):
            x_fig1[j,i-leftP]=x_fig[j,i]

    #plt.figure()
    #plt.imshow(x_fig1)                    


    

    #取 x_fig1 值
    w=x_fig1.shape[0]
    h=x_fig1.shape[1]
    
    #print(w,h)
    
    x_thresh2=np.zeros([h]).astype('int')
    for i in range(h-1):
         for j in range(w-1):
            if x_fig1[j,i]==1:
                x_thresh2[i]+=1
            if i <= 1 or i>=134: # 預留黑邊 2 pixle
                x_thresh2[i]=0


    # X方向找點
    point=0
    pos=np.array([]).astype('int')
    temp1=0
    for j in range(h-1,0,-1):
        if x_thresh2[j]<temp1 and x_thresh2[j]==0 :
            point+=1
            pos=np.append(pos,j)
        elif x_thresh2[j]>temp1 and temp1==0 :
            point+=1
            pos=np.append(pos,j)

        temp1=x_thresh2[j]




    test=np.zeros([h])
    test.fill(w)
    pos=pos.astype('int32')
    pos.sort()

    for k,j in enumerate(pos,0):    
        test[j]=0





    #結果
    print("point",point,",共",(point//2),"字元") #扣除車牌中的 '點' *
    print(pos)

    print(time.time()-t0,'s')
    
    return point//2,pos,e,s,rightP,leftP
        


def CutImg(image2,pos,e,s,rightP,leftP):    
  

    newImg=np.zeros([e-s,rightP-leftP])
#    newImg=np.zeros([34-2,132-4])
    for i in range(newImg.shape[0]):
        for j in range(newImg.shape[1]):
            newImg[i,j]=image2[i+s,j+leftP]
    count=1
    for Q in range(0,len(pos)-1,2):    
        cutImg1=np.zeros([e-s,pos[Q+1]-pos[Q]])
        for i in range (cutImg1.shape[0]):
            for j in range (cutImg1.shape[1]):
                cutImg1[i,j]=newImg[i,j+pos[Q]]
        #print(len(pos))
        #print(cutImg1.shape[1])
        if cutImg1.shape[1]<10 and Q<len(pos)-2:
            judge=(23-cutImg1.shape[1])//2
            resImg1=np.zeros([e-s,23])        
            for i in range (resImg1.shape[0]):
                for j in range (resImg1.shape[1]):
                    resImg1[i,j]=newImg[i,j+pos[Q]-judge]
            count+=1
            cv2.imwrite("cut"+str(count)+".png", resImg1)   
            continue


        count+=1
        cv2.imwrite("cut"+str(count)+".png", cutImg1)
      





