#グレースケールを二値化→論理積画像を行なうプログラム
import numpy as np
from matplotlib.image import imread, imsave
import glob, os
from PIL import Image
import cv2

"""＊＊＊各種設定＊＊＊"""
#イテレータの最初
iter_first = 5000
#イテレータの最後
iter_last = 380000
#イテレータの間隔
iter_inter = 5000
#生成した画像を保存したディレクトリ
path_gen = "./generate_image/"
#論理積画像を保存するディレクトリ
result_dir = "./result/"

path_gt = "./gt/"


#二値化
gen_fld = [os.path.basename(x) for x in glob.glob(path_gen+'*')]

for man in gen_fld:
    path_img = path_gen+man+"/"
    img_fld = [os.path.basename(x) for x in glob.glob(path_img+'*')]
    for ifolder in img_fld:
        path_img2 = path_img+ifolder+"/"
        img_fld2 = [os.path.basename(x) for x in glob.glob(path_img2+'*')]
        #二値化処理
        for ifile in img_fld2:
            img = cv2.imread(path_img2+ifile,0)
            ret, th2 = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)
            cv2.imwrite(path_img2+ifile,th2)

#論理積をとって画像を生成
for man in gen_fld:
    path_img = path_gen+man+"/"
    img_fld = [os.path.basename(x) for x in glob.glob(path_img+'*')]
    for ifolder in img_fld:
        path_img2 = path_img+ifolder+"/"
        for num in range(iter_first,iter_last+1,iter_inter):
            img = imread(path_img2+"iter_"+str(num)+".jpg")
            if(num == iter_first):
                mask_img = img
            else:
                make = cv2.bitwise_and(img,img, mask = mask_img)
                mask_img = make

        #
        res_dir = result_dir+man+"/"
        if not os.path.exists(res_dir):
            os.makedirs(res_dir)
        cv2.imwrite(res_dir+str(ifolder)+".jpg",mask_img)

print("complete")

