#--AI1.py--
import time
from PARAM2 import *  #攝影鏡頭擷取影片的參數
import cv2            #open cv是影像分析所使用的模組
import numpy as np    #矩陣運算的模組
from  motorm import turn  #控制馬達運轉的函數
#from LOCENG import locate  #取出畫面中特定顏色(green)的位置和大小所形成的框架
from LOCREC import locate  #取出畫面中特定顏色(green)的位置和大小所形成的框架
from time import sleep     #sleep是讓程式的執行休息若干秒鐘

#--------PICTURE------
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,1080)
sleep(2)  #讓攝影鏡頭有足夠的時間截取影像足夠清晰的內容

print('Lx,Ly,Lx2,Ly2=',Lx,Ly,Lx2,Ly2)
ss='A2'
jt=0; NP=0;  
while(jt < 60 and cap.isOpened()):
    ret,frame = cap.read(); jt+=1; 
    frame= cv2.resize(frame, (Lx,Ly), interpolation=cv2.INTER_AREA)
    imgc= cv2.resize(frame, (Lx2*2,Ly2*2), interpolation=cv2.INTER_AREA)
    if(ret==False): break
    img=np.copy(frame)
    img2=np.copy(img)
    NN,BOX,img24=locate(img2)
    print(jt,NN,BOX)
    if(NN==0): WDSX=0; print('jt=',jt,'null NN=',NN,BOX); 
    for t in range(NN):
        NP+=1
        x1=BOX[t][0]*F; x2=BOX[t][1]*F; y1=BOX[t][2]*F; y2=BOX[t][3]*F;
        cv2.rectangle(img2,(x1,y1),(x2,y2),(5,0,255),6)
        cv2.rectangle(img24,(x1,y1),(x2,y2),(0,120,0),2)
        img3=img[y1:y2,x1:x2,:]
        img3=cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY)
        #---攝影鏡頭截取到的文字圖框被儲存為一個檔案檔案的名稱定義如下
        fn='PNG/'+ss+'_'+str(NP).zfill(3)+'.png'
        #---為了避免檔案被覆寫,每次要執行程式之前請先確定更改新的檔名
        cv2.imwrite(fn,img3)
        #cv2.imshow('img3NN'+str(t),img3)
    DR=1
    imgb= cv2.resize(img2, (Lx2*3,Ly2*3), interpolation=cv2.INTER_AREA)
    print('jt=',jt,' NN=',NN,BOX,img3.shape)
    #cv2.imshow('imgb',imgb)
    if cv2.waitKey(1) & 0xFF == ord('q'): break
    turn(0.2,0.2,0.1); turn(0,0,0.5) #自駕車前進一些準備取得新的相片
    #cv2.waitKey(0)
    #if(jt%10==0): sleep(4)
    cv2.destroyAllWindows()
cv2.destroyAllWindows()





